public IComputer getService(String type){ IComputer service = null; if ("A".equals(type)) { service = new HuaWeiIComputer(); } if ("B".equals(type)) { service = new AppleIComputer(); } //生产电脑 service.method(); return service; }
虽然实现了一定的解耦,不将代码都放一块了,但如果添加产品C,工厂中的方法得改变
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicIComputer(String type){ IComputer service = null; if ("A".equals(type)) { service = new HuaWeiIComputer(); } if ("B".equals(type)) { service = new AppleIComputer(); } if ("C".equals(type)) { service = new XiaoMiIComputer(); } //生产电脑 service.method(); return service; }
if (aLocale.hasExtensions()) { String caltype = aLocale.getUnicodeLocaleType("ca"); if (caltype != null) { switch (caltype) { case"buddhist": cal = new BuddhistCalendar(zone, aLocale); break; case"japanese": cal = new JapaneseImperialCalendar(zone, aLocale); break; case"gregory": cal = new GregorianCalendar(zone, aLocale); break; } } }
publicclassHuaWeiComputerFactoryimplementsIComputerFactory{ @Override public IComputer getService(){ returnnew HuaWeiIComputer(); } } publicclassAppleComputerFactoryimplementsIComputerFactory{ @Override public IComputer getService(){ returnnew AppleIComputer(); } }
调用方
1 2 3 4 5 6 7 8 9 10 11 12
public IComputer getService(String type){ IComputer service = null; if ("A".equals(type)) { HuaWeiComputerFactory aFactory = new HuaWeiComputerFactory(); service = aFactory.getService(); } if ("B".equals(type)) { AppleComputerFactory bFactory = new AppleComputerFactory(); service = bFactory.getService(); } return service; }
public IComputer getService(String type){ IComputer service = null; if ("A".equals(type)) { HuaWeiComputerFactory aFactory = new HuaWeiComputerFactory(); service = aFactory.getService(); } if ("B".equals(type)) { AppleComputerFactory bFactory = new AppleComputerFactory(); service = bFactory.getService(); } if ("C".equals(type)) { XiaoMiComputerFactory cFactory = new XiaoMiComputerFactory(); service = cFactory.getService(); } //生产电脑 service.method(); return service; }