抽象工廠模式
抽象工廠UML.png
interface Shoe{
void wear();
}
定義鞋類接口,定義公共方法穿鞋子。
interface Hat{
void wear();
}
定義帽子類接口,定義公共方法戴帽子。
class LeatherShoe implements Shoe{
public LeatherShoe(){
}
public void wear(){
//穿皮鞋
}
}
皮鞋實體類
class ClothShoe implements Shoe{
public ClothShoe(){
}
public void wear(){
//穿布鞋
}
}
布鞋實體類
class LeatherHat implements Hat{
public LeatherHat(){
}
public void wear(){
//帶皮帽
}
}
皮帽實體類
class ClothHat implements Hat{
public ClothHat(){
}
public void wear(){
//戴草帽
}
}
草帽實體類
interface Factory{
Shoe createShoe();
Hat creatHat();
}
工廠接口
class ClothFactory implements Factory{
public Shoe createShoe(){
ClothShoe clothShoe = new ClothShoe();
return clothShoe;
}
public Hat creatHat(){
ClothHat clothHat = new ClothHat();
return clothHat;
}
}
布料工廠類
class LeatherFactory implements Factory{
public Shoe createShoe(){
LeatherShoe leatherShoe = new LeatherShoe();
return leatherShoe;
}
public Hat creatHat(){
LeatherHat leatherHat = new LeatherHat();
return leatherHat;
}
}
皮料工廠類
class Client{
public static void main(String args[]){
Shoe mShoe;
Hat mHat;
Factory mFactory;
mFactory = new ClothFactory();//創(chuàng)建布料工廠
mShoe = mFactory.createShoe();//工廠生產(chǎn)鞋
mHat = mFactory.creatHat();//工廠生產(chǎn)帽子
mShoe.wear();//穿布鞋
mHat.wear();//戴帽子
}
}
客戶端
優(yōu)點
- 抽象工廠模式隔離了具體類的生成,使得客戶并不需要知道什么被創(chuàng)建。由于這種隔離, 更換一個具體工廠就變得相對容易,所有的具體工廠都實現(xiàn)了抽象工廠中定義的那些公共接 口,因此只需改變具體工廠的實例,就可以在某種程度上改變整個軟件系統(tǒng)的行為。
- 當一個產(chǎn)品族中的多個對象被設(shè)計成一起工作時,它能夠保證客戶端始終只使用同一個產(chǎn) 品族中的對象。
- 增加新的產(chǎn)品族很方便,無須修改已有系統(tǒng),符合“開閉原則”。
缺點
- 增加新的產(chǎn)品等級結(jié)構(gòu)麻煩,需要對原有系統(tǒng)進行較大的修改,甚至需要修改抽象層代碼, 這顯然會帶來較大的不便,違背了“開閉原則”。