【设计模式】简单工厂模式

简述

简单工厂模式,通过一个方法获取需要的Bean。如果一个工厂方法可获取不同的类,那么可通过入参判断,入参也许为字符串、数字或者枚举。

简单的例子

最简单的就是通过流程判断来确定获取哪个类的实例。

public class OrderHandlerFactory {

	public static OrderHandler getOrderHandler(OrderHandlerType orderHandlerType) {
		if (orderHandlerType == null) {
			return null;
		}

		switch (orderHandlerType) {
		case GOODS_ORDER:
			return new GoodsOrderHandler();
		case TELEPHONE_CHARGE_ORDER:
			return new TelephoneChargeOrderHandler();
		default:
			return null;
		}

	}

}

如果日后需增加或减少生成的类,需对流程判断进行修改容易出错,那么通过设置好的映射生成指定类。这里的映射维护在枚举中,当然维护在一个Map中也行。

public class OrderHandlerFactory {

	public static OrderHandler getOrderHandler(OrderHandlerType orderHandlerType) {
		if (orderHandlerType == null) {
			return null;
		}

		try {
			return (OrderHandler)orderHandlerType.getHandlerClass().newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}
	
}

具体例子位于https://github.com/nicchagil/design-pattern-exercise-with-java

JDK中的例子,比如Proxy.newProxyInstance(),个人觉得也是简单工厂模式,根据入参生成实例,只不过它生成实例的过程是非常复杂的。

posted @ 2017-06-15 22:15  nick_huang  阅读(250)  评论(0编辑  收藏  举报