我們一起聊聊抽象工廠模式(AbstractFactoty)
今天給大家介紹《Java極簡設計模式》的第02章,抽象工廠模式(AbstractFactoty),多一句沒有,少一句不行,用最簡短的篇幅講述設計模式最核心的知識,好了,開始今天的內容。
一、概述
提供一個創建一系列相關或相互依賴對象的接口,而無需指定它們具體的類。
二、為何使用
工廠模式是我們最常用的模式了,著名的Jive論壇 ,就大量使用了工廠模式,工廠模式在Java程序系統可以說是隨處可見。
為什么工廠模式是如此常用?因為工廠模式就相當于創建實例對象的new,我們經常要根據類Class生成實例對象,如A a=new A() 工廠模式也是用來創建實例對象的,所以以后new時就要多個心眼,是否可以考慮實用工廠模式,雖然這樣做,可能多做一些工作,但會給你系統帶來更大的可擴展性和盡量少的修改量。
三、實用性
- 一個系統要獨立于它的產品的創建、組合和表示時。
- 一個系統要由多個產品系列中的一個來配置時。
- 當你要強調一系列相關的產品對象的設計以便進行聯合使用時。
- 當你提供一個產品類庫,而只想顯示它們的接口而不是實現時。
四、參與者
- AbstractFactory 聲明一個創建抽象產品對象的操作接口。
- ConcreteFactory 實現創建具體產品對象的操作。
- AbstractProduct 為一類產品對象聲明一個接口。
- ConcreteProduct 定義一個將被相應的具體工廠創建的產品對象。實現AbstractProduct接口。
- Client 僅使用由AbstractFactory和AbstractProduct類聲明的接口
五、類圖
圖片
六、示例
- AbstractFactory
定義抽象工程類IAnimalFactory
public interface IAnimalFactory {
/**
* 定義創建Icat接口實例的方法
* @return
*/
ICat createCat();
/**
* 定義創建IDog接口實例的方法
* @return
*/
IDog createDog();
}
- ConcreteFactory
創建抽象工廠類的兩個實現類,WhiteAnimalFactory和BlackAnimalFactory
public class WhiteAnimalFactory implements IAnimalFactory {
public ICat createCat() {
return new WhiteCat();
}
public IDog createDog() {
return new WhiteDog();
}
}
public class BlackAnimalFactory implements IAnimalFactory {
@Override
public ICat createCat() {
return new BlackCat();
}
public IDog createDog() {
return new BlackDog();
}
}
- AbstractProduct
定義抽象工廠中要生產的抽象產品接口ICat和IDog
public interface ICat {
/**
* 定義方法
*/
void eat();
}
public interface IDog {
/**
* 定義方法
*/
void eat();
}
- ConcreteProduct
創建產品的實現類BlackCat、BlackDog、WhiteCat、WhiteDog
public class BlackCat implements ICat {
@Override
public void eat() {
System.out.println("The black cat is eating!");
}
}
public class BlackDog implements IDog {
@Override
public void eat() {
System.out.println("The black dog is eating");
}
}
public class WhiteCat implements ICat {
@Override
public void eat() {
System.out.println("The white cat is eating!");
}
}
public class WhiteDog implements IDog {
@Override
public void eat() {
System.out.println("The white dog is eating!");
}
}
- Client
定義一個測試類Test
public class Test {
public static void main(String[] args) {
IAnimalFactory blackAnimalFactory = new BlackAnimalFactory();
ICat blackCat = blackAnimalFactory.createCat();
blackCat.eat();
IDog blackDog = blackAnimalFactory.createDog();
blackDog.eat();
IAnimalFactory whiteAnimalFactory = new WhiteAnimalFactory();
ICat whiteCat = whiteAnimalFactory.createCat();
whiteCat.eat();
IDog whiteDog = whiteAnimalFactory.createDog();
whiteDog.eat();
}
}
- 輸出結果
The black cat is eating!
The black dog is eating
The white cat is eating!
The white dog is eating!
七、總結
由此可見,工廠方法確實為系統結構提供了非常靈活強大的動態擴展機制,只要我們更換一下具體的工廠方法,系統其他地方無需一點變換,就有可能將系統功能進行改頭換面的變化。