工厂模式
一般建立对象的方法是: Sample sample = new Sample(); 通过new关键词和类的构造方法来建立一个对象,可以通过向构造方法传递参数,并在构造方法中完成一些初始化的工作。但是,如果初始化的工作非常多,采用这样的方法实在不是明智的,而应该采用将创建实例的工作与使用实例的工作分开的原则,而这就是工厂模式。
工厂模式用于创建复杂的对象,创建复杂的对象是指在创建对象时需要大量的初始化工作。工厂模式将创建实例的工作与使用实例的工作分开。在一个接口拥有多个实现类时也可以使用工厂模式来建立子类的对象。
按照面向接口编程的原则,我们可以把功能类抽象成接口。首先建立一个接口Sample,假如Sample有两个实现类SampleA和SampleB,创建SampleA和SampleB的工厂方法如下:
- public class Factory {
- public static Sample createSample(int which){
- if (which==1) {
- return new SampleA();
- } else if (which==2)
- return new SampleB();
- }
- }
- }
这样就可以调用Factory.createSample(1)来创建对象了。
抽象工厂
工厂模式中有: 工厂方法(Factory Method) 抽象工厂(Abstract Factory)。抽象工厂(Abstract Factory)处理更为复杂对象创建工作。
例:
- // 产品 Plant接口
- public interface Plant { }
- //具体产品PlantA,PlantB
- public class PlantA implements Plant {
- public PlantA () {
- System.out.println("create PlantA !");
- }
- public void doSomething() {
- System.out.println(" PlantA do something ...");
- }
- }
- public class PlantB implements Plant {
- public PlantB () {
- System.out.println("create PlantB !");
- }
- public void doSomething() {
- System.out.println(" PlantB do something ...");
- }
- }
- // 产品 Fruit接口
- public interface Fruit { }
- //具体产品FruitA,FruitB
- public class FruitA implements Fruit {
- public FruitA() {
- System.out.println("create FruitA !");
- }
- public void doSomething() {
- System.out.println(" FruitA do something ...");
- }
- }
- public class FruitB implements Fruit {
- public FruitB() {
- System.out.println("create FruitB !");
- }
- public void doSomething() {
- System.out.println(" FruitB do something ...");
- }
- }
- // 抽象工厂方法
- public interface AbstractFactory {
- public Plant createPlant();
- public Fruit createFruit() ;
- }
- //具体工厂方法
- public class FactoryA implements AbstractFactory {
- public Plant createPlant() {
- return new PlantA();
- }
- public Fruit createFruit() {
- return new FruitA();
- }
- }
- public class FactoryB implements AbstractFactory {
- public Plant createPlant() {
- return new PlantB();
- }
- public Fruit createFruit() {
- return new FruitB();
- }
- }
工厂方法模式与简单工厂模式再结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具体类上。
工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口,或者有共同的抽象父类。
当系统扩展需要添加新的产品对象时,仅仅需要添加一个具体对象以及一个具体工厂对象,原有工厂对象不需要进行任何修改,也不需要修改客户端,很好的符合了"开放-封闭"原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法,扩展性不好。