简单工厂模式是类的创建模式,又叫做静态工厂方法模式(Static Factory Method Pattern)
目的: 封装对象的创建过程,用户只需要传入指定的参数即可获取相应的实例。
优点:封装了实例的创建过程,客户端只需要消费实例;进行了责任分割。
有一个水果店,中出售两种水果;一种是苹果,一种是橘子;客户只需要指定自己需要的什么什么类型的苹果或者橘子就可以了,而不必知道这些水果是怎么种植,运输加工的。
/** * 水果接口 * @author Lenovo * @version $Id: Fruit.java, v 0.1 2014年9月20日 下午4:42:48 Lenovo Exp $ */ public interface Fruits { /** * 获取水果的名称 * * @return 水果的名称 */ public String getName(); }
/** * 定义苹果类 * @author Lenovo * @version $Id: Apple.java, v 0.1 2014年9月20日 下午4:45:18 Lenovo Exp $ */ public class Apple implements Fruits { /** * 水果的名称 */ private String name; /** * Getter method for property <tt>name</tt>. * * @return property value of name */ public String getName() { return name; } /** * Setter method for property <tt>name</tt>. * * @param name value to be assigned to property name */ public void setName(String name) { this.name = name; } public Apple(String name) { super(); this.name = name; } } /** * * @author Lenovo * @version $Id: Orange.java, v 0.1 2014年9月20日 下午4:53:58 Lenovo Exp $ */ public class Orange implements Fruits { /** * 橘子的名称 */ String name; /** * Getter method for property <tt>name</tt>. * * @return property value of name */ public String getName() { return name; } /** * Setter method for property <tt>name</tt>. * * @param name value to be assigned to property name */ public void setName(String name) { this.name = name; } public Orange(String name) { super(); this.name = name; } } /** * * 水果简单工厂 * 简单工厂模式,就是根据传入的参数决定创建出哪一个产品 * * 优点: * 简单工厂模式的核心就是工厂类。 这个类包含必要的逻辑判断,可以决定在什么时候创建什么产品;而客户端则可以免除直接创建产品的对象 * 的责任,而仅仅负责消费产品。 * 缺点: * 当产品类有多层次的等级结构时,只有工厂类以不变应万变。 * 由于简单工厂模式使用的是静态方法作为工厂方法,而静态方法无法由子类继承,因此工厂角色无法形成基于继承的等级结构。 * @author Lenovo * @version $Id: FruitFactory.java, v 0.1 2014年9月20日 下午4:41:53 Lenovo Exp $ */ public class FruitFactory { enum FRUITS { APPLE, ORANGE; } public static Fruits factory(FRUITS type) { switch (type) { case APPLE: return new Apple("花牛苹果"); case ORANGE: return new Orange("秋山蜜柑"); default: throw new UnsupportedOperationException(); } } } /** * * @author Lenovo * @version $Id: Client.java, v 0.1 2014年9月20日 下午5:00:10 Lenovo Exp $ */ public class Client { public static void main(String[] args) { Fruits f = FruitFactory.factory(FRUITS.APPLE); LoggerUtils.info(f.getName()); Fruits orange = FruitFactory.factory(FRUITS.ORANGE); LoggerUtils.info(orange.getName()); } }