工廠方法模式
設計模式使人們可以更加簡單方便的複用成功的設計和體系結構,設計模式中也遵循着一些原則,而這些原則也是JAVA開發中所提倡的,比如針對接口編程而不是針對實現編程,優先使用對象組合而不是類繼承等,總共有六大原則,感興趣的朋友可以自行深入瞭解。
設計模式總體可分爲以下三類
創建型模式,共五種:工廠方法模式、抽象工廠模式、單例模式、建造者模式、原型模式。
結構型模式,共七種:適配器模式、裝飾器模式、代理模式、外觀模式、橋接模式、組合模式、享元模式。
行爲型模式,共十一種:策略模式、模板方法模式、觀察者模式、迭代子模式、責任鏈模式、命令模式、備忘錄模式、狀態模式、訪問者模式、中介者模式、解釋器模式。
其關係如圖所示。
接下來,進入工廠方法模式
定義
定義一個用於創建對象的接口,讓子類決定實例化哪一個類,工廠方法模式使一個類的實例化延遲到其子類。
使用場景
1. 當一個類不知道它所必須創建的對象的類的時候。
2. 當一個類希望由它的子類來指定它所創建的對象的時候。
3. 當類將創建對象的職責委託給多個幫助子類中的某一個,並且你希望將哪一個幫助子類是代理者這一信息局部化的時候。
結構
實現
先創建接口類Product
public interface Product {
void method();
}
Product的具體實現
public class ProductA implements Product {
public void method() {
System.out.println("this is ProductA's Method");
}
}
public class ProductB implements Product {
public void method() {
System.out.println("this is ProductB's Method");
}
}
工廠類Factory
public class Factory {
public Product createProduct(String type){
if("ProductA".equals(type)){
return new ProductA();
}else if("ProductB".equals(type)){
return new ProductB();
}else{
return null;
}
}
}
我們來測試一下
public class FactoryTest {
public static void main(String[] args) {
Factory factory = new Factory();
Product product = factory.createProduct("ProductA");
product.method();
}
}
輸出結果爲:this is ProductA’s Method
從以上代碼我們可以理解工廠方法的實現,同時也發現一些問題,比如當傳遞的參數是錯誤的時候,得到的對象是空的,這顯然不太雅觀,於是我們對Factory類進行一下改造。
public class Factory {
public Product createProductA(){
return new ProductA();
}
public Product createProductB(){
return new ProductB();
}
}
測試代碼
public class FactoryTest {
public static void main(String[] args) {
Factory factory = new Factory();
Product product = factory.createProductB();
product.method();
}
}
測試結果:this is ProductB’s Method
從測試代碼中可以發現其實Factory類可以不需要創建實例,我們可以把工廠方法設置成靜態的,因此工廠方法模式又變種升級成靜態工廠方法模式
public class Factory {
public static Product createProductA(){
return new ProductA();
}
public static Product createProductB(){
return new ProductB();
}
}
測試代碼
public class FactoryTest {
public static void main(String[] args) {
Product product = Factory.createProductB();
product.method();
}
}
測試結果:this is ProductB’s Method
實際應用中,我們更偏向於使用靜態的工廠方法模式