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,其一缺点为当有新的产品加入到系统中时还必须修改工厂类。








































二:结构
三:实际应用
- EJB技术构架中




四:适用情形
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》