简单工厂模式
又称静态工厂方法模式(Static Factory Method Pattern)
分析实现步骤
将在类中直接创建对象(new),提取到一个公共的工厂类中,达到创建对象和业务类解耦目的
代码实现

- 定义抽象类
- 实现具体类
- 定义简单工厂类
- 实现预定方法
- 客户端测试
- 分析
定义简单工厂类
/*** 简单工厂模式*/public class SimpleFactory {public static AbstractCake createCake(String orderType) {AbstractCake cake = null;if (orderType.equals("水果")) {cake = new fruitCake();cake.setName(orderType + "蛋糕 ");} else if (orderType.equals("奶油")) {cake = new CreamCake();cake.setName(orderType + "蛋糕 ");} else {System.out.println("暂不支持的蛋糕类型");return cake;}return cake;}}
实现预定方法
/*** 预定方法实现类*/public class OrderCake {public OrderCake(){setFactory();}private void setFactory() {String orderType;do {orderType = getType();//获取简单(静态)工厂AbstractCake cake = SimpleFactory.createCake(orderType);if(cake != null) {cake.prepare();cake.bake();cake.box();cake.send();} else {System.out.println("预定失败");break;}}while(true);}//输入蛋糕类型private String getType() {try {BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));System.out.println("请输入蛋糕类型:");String str = strin.readLine();return str;} catch (IOException e) {e.printStackTrace();return "";}}}
由上代码可知:此时上新一个新品蛋糕,只需新增一个新品蛋糕类,修改SimpleFactory工厂类一处即可实现需求调整。
新需求:如果此时需要生产同一类型的蛋糕不同口味,如:奶油蛋糕的中国口味,奶油蛋糕的美国口味。
实现方式一:细化蛋糕类,新增一种口味蛋糕当做一个新品蛋糕(即把原来的奶油蛋糕类细化成不同口味的奶油蛋糕)
实现方式二:复制多份简单工厂,如一个中国简单工厂,一个美国简单工厂
方式一、二可以实现,但考虑到项目规模,可维护性和可扩展性来说,不是一个很好的方案。有没有什么好的方式可以很好的解决这个问题?==》工厂方法模式
框架或项目源码分析
JDK中的Calendar类使用的是简单工厂模式
public static Calendar getInstance(){return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));}private static Calendar createCalendar(TimeZone zone, Locale aLocale){CalendarProvider provider =LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale).getCalendarProvider();if (provider != null) {try {return provider.getInstance(zone, aLocale);} catch (IllegalArgumentException iae) {// fall back to the default instantiation}}Calendar cal = null;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;}}}if (cal == null) {// If no known calendar type is explicitly specified,// perform the traditional way to create a Calendar:// create a BuddhistCalendar for th_TH locale,// a JapaneseImperialCalendar for ja_JP_JP locale, or// a GregorianCalendar for any other locales.// NOTE: The language, country and variant strings are interned.if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {cal = new BuddhistCalendar(zone, aLocale);} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"&& aLocale.getCountry() == "JP") {cal = new JapaneseImperialCalendar(zone, aLocale);} else {cal = new GregorianCalendar(zone, aLocale);}}return cal;}
应用场景
对于产品种类相对较少的情况,考虑使用简单工厂模式。使用简单工厂模式的客户端只需要传入工厂类的参数,不需要关心如何创建对象的逻辑,可以很方便地创建所需产品。
