在创建对象时不向客户暴露内部细节,并提供一个创建对象的通用接口。
简单工厂把实例化操作单独放到一个类中,这个类就是简单工厂类,让简单工厂类来决定应该实例化哪个具体子类。这样做的好处是,能够把客户端和具体子类的实现解耦,客户端不再需要知道有哪些子类以及应当实例化哪个子类。
类图

实现
1 2 3
| public interface Product { }
|
1 2 3
| public class ConcreteProduct1 implements Product { }
|
1 2 3
| public class ConcreteProduct2 implements Product {
}
|
1 2 3
| public class ConcreteProduct3 implements Product {
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class SimpleFactory {
public Product createProduct(int type) { if (type == 1) { return new ConcreteProduct1(); } else if (type == 2) { return new ConcreteProduct2(); } else { return new ConcreteProduct3(); } }
}
|
1 2 3 4 5 6 7 8
| public class Client {
public static void main(String[] args) { SimpleFactory simpleFactory = new SimpleFactory(); Product product = simpleFactory.createProduct(1); }
}
|