建立型模式--工廠方法模式(Factory Method)
阿新 • • 發佈:2019-01-06
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,其一缺點為當有新的產品加入到系統中時還必須修改工廠類。
publicinterfacepublic Fruit createFruit();
}
publicclass AppleFactory implements FruitFactory {
public Fruit createFruit()
{
returnnew Apple();
}
}
publicclass Client{
publicstatic Fruit getEatFruit()
{
Fruit fruit=null;
FruitFactory fruitFactory
fruit=fruitFactory.createFruit();
fruit.pick();
fruit.peel();
return fruit;
}
publicstaticvoid main(String args[])
{
getEatFruit();
}
}
//這樣有新的產品加入時,只要加入對應的Factory,不用修改Simple Factory 中建立部分的程式碼
二:結構
三:實際應用
- EJB技術構架中
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》