标签:
工厂模式专门负责将有大量的共同的接口的类实例化。工程模式可以决定哪一个类实例化,不必事先知道每次要实例化哪一个类。
工厂模式有三种形态:
1)简单工厂模式(Simple Factory):又称静态工厂方法模式
2)工厂方法模式(Factory Method):又称为多形性工厂模式
3)抽象工厂模式(Abstract Factory):又称为工具箱模式
PS:简单工厂模式和工厂方法模式可以统称为普通工厂模式
public interface Animal { void sound(); } public class Cat implements Animal{ @Override public void sound() { System.out.println("喵喵。。。"); } } public class Dog implements Animal { @Override public void sound() { System.out.println("旺旺。。。"); } }
public class SimpleAnimalFactory { public static Animal keep(String arg) { Animal animal = null; switch(arg) { case "cat": animal = new Cat(); break; case "dog": animal = new Dog(); break; } return animal; } }
public interface AnimalFactory { Animal keep(); } public class CatFactory implements AnimalFactory { @Override public Animal keep() { return new Cat(); } } public class DogFactory implements AnimalFactory { @Override public Animal keep() { return new Dog(); } }
可以看出,每增加一种Animal就需要增加该类的工厂,当Animal种类越来越多时就会造成工厂泛滥。
public interface Flower { void color(); } public class Rose implements Flower { @Override public void color() { System.out.println("红玫瑰"); } } public class Lily implements Flower { @Override public void color() { System.out.println("白百合"); } }
public abstract class AbstractFactory { abstract Animal keep(); abstract Flower grow(); } public class DefaultFactory extends AbstractFactory { @Override Animal keep() { return new Dog(); } @Override Flower grow() { return new Rose(); } }
测试
public class Test { public static void main(String[] args) { Animal a1 = SimpleAnimalFactory.keep("dog"); a1.sound(); AnimalFactory af = new CatFactory(); Animal a2 = af.keep(); a2.sound(); AbstractFactory factory = new DefaultFactory(); Animal animal = factory.keep(); animal.sound(); Flower flower = factory.grow(); flower.color(); } }
标签:
原文地址:http://www.cnblogs.com/wangj1130/p/4842875.html