创建型模式--工厂方法模式(Factory Method)

阅读更多

 Factory Method:Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

工厂方法模式又叫虚拟构造子(Virtual Constructor)模式。

一:引入

      Simple Factory在一定程度上支持OCP,但并没有完全支持OCP,其一缺点为当有新的产品加入到系统中时还必须修改工厂类。

public   interface  FruitFactory  ... {
    
public Fruit createFruit();
}


public   class  AppleFactory  implements  FruitFactory  ... {
    
public Fruit createFruit()
    
...{
        
return new Apple();
    }

}



public   class  Client ... {

       
public static  Fruit getEatFruit()
       
...{
           Fruit fruit
=null;
           FruitFactory fruitFactory
=new AppleFactory();
           fruit
=fruitFactory.createFruit();
           fruit.pick();
           fruit.peel();
           
           
return fruit;
           
       }

       
       
public static void main(String args[])
       
...{
           getEatFruit();
       }

      
}

// 这样有新的产品加入时,只要加入对应的Factory,不用修改Simple Factory 中创建部分的代码

 

二:结构

创建型模式--工厂方法模式(Factory Method)_第1张图片

三:实际应用

  1. EJB技术构架中
Context ctx = new  InitContext();
EmployeeHome home
= (EmployeeHome )ctx.lookup( " Employee " ); // 得到Concrete Factory (EmployeeHome)
Employee emp = home.create( 1001 , " andy " , " Smith " ); // 创建Concrete Product(Employee)
emp.setTel( " 010-1234343 " );

 

四:适用情形

Use the Factory Method pattern when

  • a class can't anticipate the class of objects it must create.
  • a class wants its subclasses to specify the objects it creates.
  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

接口稳定,创建的具体类不可预料,经常变;

当然如果这个类十分稳定,就没有必要用Factory模式,如String类,十分稳定,没有其它的子类。

参考文献:
1:阎宏,《Java与模式》,电子工业出版社
2:Eric Freeman & Elisabeth Freeman,《Head First Design Pattern》,O'REILLY
3:GOF ,《designpatterns-elements.of.reuseable.object-oriented.software》



你可能感兴趣的:(出版,Apple,EJB)