工厂类:
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) { // 此方法不必关心 .....
....
} }