《程序员修炼之道》-读书笔记六-工厂模式下的伪DI依赖注入

时间:2019-09-22
本文章向大家介绍《程序员修炼之道》-读书笔记六-工厂模式下的伪DI依赖注入,主要包括《程序员修炼之道》-读书笔记六-工厂模式下的伪DI依赖注入使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

工厂类:

 1 public class AgentFinderFactory {
 2 
 3   private static AgentFinderFactory singleton;
 4 
 5   private AgentFinderFactory() {
 6   }
 7 
 8   public static AgentFinderFactory getInstance() {
 9     if (singleton == null) {
10       singleton = new AgentFinderFactory(); // 单例模式,保证此工厂类的唯一性
11     }
12     return singleton;
13   }
14 
15   public AgentFinder getAgentFinder(String agentType) { // 根据类型,选择输出处理类
16     AgentFinder finder = null;
17     switch (agentType) {
18     case "spreadsheet":
19       finder = new SpreadsheetAgentFinder();
20       break;
21     case "webservice":
22       finder = new WebServiceAgentFinder();
23       break;
24     default:
25       finder = new WebServiceAgentFinder();
26       break;
27     }
28     return finder;
29   }
30 }

业务类:

public class HollywoodServiceWithFactory {

  public static List<Agent> getFriendlyAgents(String agentFinderType) {
    AgentFinderFactory factory = AgentFinderFactory.getInstance(); // 获取工厂类,此时工厂类初步加载
    AgentFinder finder = factory.getAgentFinder(agentFinderType); // 根据传入所有类型,获取所需操作对象
    List<Agent> agents = finder.findAllAgents(); // 执行业务
    List<Agent> friendlyAgents = filterAgents(agents, "Java Developers");
    return friendlyAgents;
  }

  public static List<Agent> filterAgents(List<Agent> agents, String agentType) { // 此方法不必关心
   .....
  ....
} }

原文地址:https://www.cnblogs.com/Deters/p/11568974.html