zoukankan      html  css  js  c++  java
  • 《程序员修炼之道》-读书笔记六-工厂模式下的伪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) { // 此方法不必关心
       .....
      ....
    } }
  • 相关阅读:
    mybatis入门-1
    try-with-resources 在捕获异常之后自动释放资源 try(){}
    mybatis配置logback
    使用原生的jdbc连接数据库进行查询
    java中的反射
    ajax实现搜索自动补全
    java IO-1 File 2019-07-24
    VMware历史版本
    Centos8.3-NIS
    用户管理
  • 原文地址:https://www.cnblogs.com/Deters/p/11568974.html
Copyright © 2011-2022 走看看