工厂模式

        一般建立对象的方法是: Sample sample = new Sample(); 通过new关键词和类的构造方法来建立一个对象,可以通过向构造方法传递参数,并在构造方法中完成一些初始化的工作。但是,如果初始化的工作非常多,采用这样的方法实在不是明智的,而应该采用将创建实例的工作与使用实例的工作分开的原则,而这就是工厂模式。

        工厂模式用于创建复杂的对象,创建复杂的对象是指在创建对象时需要大量的初始化工作。工厂模式将创建实例的工作与使用实例的工作分开。在一个接口拥有多个实现类时也可以使用工厂模式来建立子类的对象。

        按照面向接口编程的原则,我们可以把功能类抽象成接口。首先建立一个接口Sample,假如Sample有两个实现类SampleA和SampleB,创建SampleA和SampleB的工厂方法如下:

java 代码
  1. public class Factory {   
  2.   public static Sample createSample(int which){   
  3.      if (which==1) {   
  4.         return new SampleA();   
  5.      } else if (which==2)   
  6.         return new SampleB();   
  7.      }   
  8.   }   
  9. }  

这样就可以调用Factory.createSample(1)来创建对象了。

抽象工厂
        工厂模式中有: 工厂方法(Factory Method) 抽象工厂(Abstract Factory)。抽象工厂(Abstract Factory)处理更为复杂对象创建工作。

工厂模式

       例:

java 代码
  1. // 产品 Plant接口    
  2. public interface Plant { }    
  3. //具体产品PlantA,PlantB    
  4. public class PlantA implements Plant {    
  5.   
  6.  public PlantA () {    
  7.   System.out.println("create PlantA !");    
  8.  }    
  9.   
  10.  public void doSomething() {    
  11.   System.out.println(" PlantA do something ...");    
  12.  }    
  13. }    
  14. public class PlantB implements Plant {    
  15.  public PlantB () {    
  16.   System.out.println("create PlantB !");    
  17.  }    
  18.   
  19.  public void doSomething() {    
  20.   System.out.println(" PlantB do something ...");    
  21.  }    
  22. }    
  23. // 产品 Fruit接口    
  24. public interface Fruit { }    
  25. //具体产品FruitA,FruitB    
  26. public class FruitA implements Fruit {    
  27.  public FruitA() {    
  28.   System.out.println("create FruitA !");    
  29.  }    
  30.  public void doSomething() {    
  31.   System.out.println(" FruitA do something ...");    
  32.  }    
  33. }    
  34. public class FruitB implements Fruit {    
  35.  public FruitB() {    
  36.   System.out.println("create FruitB !");    
  37.  }    
  38.  public void doSomething() {    
  39.   System.out.println(" FruitB do something ...");    
  40.  }    
  41. }    
  42. // 抽象工厂方法    
  43. public interface AbstractFactory {    
  44.  public Plant createPlant();    
  45.  public Fruit createFruit() ;    
  46. }    
  47. //具体工厂方法    
  48. public class FactoryA implements AbstractFactory {    
  49.  public Plant createPlant() {    
  50.   return new PlantA();    
  51.  }    
  52.  public Fruit createFruit() {    
  53.   return new FruitA();    
  54.  }    
  55. }    
  56. public class FactoryB implements AbstractFactory {    
  57.  public Plant createPlant() {    
  58.   return new PlantB();    
  59.  }    
  60.  public Fruit createFruit() {    
  61.   return new FruitB();    
  62.  }    
  63. }   

        工厂方法模式与简单工厂模式再结构上的不同不是很明显。工厂方法类的核心是一个抽象工厂类,而简单工厂模式把核心放在一个具体类上。

  工厂方法模式之所以有一个别名叫多态性工厂模式是因为具体工厂类都有共同的接口,或者有共同的抽象父类。

  当系统扩展需要添加新的产品对象时,仅仅需要添加一个具体对象以及一个具体工厂对象,原有工厂对象不需要进行任何修改,也不需要修改客户端,很好的符合了"开放-封闭"原则。而简单工厂模式在添加新产品对象后不得不修改工厂方法,扩展性不好。