工廠方法模式
-
介紹
- 結構圖:
- 結構圖:
- 定義
定義一個用於船艦對象的接口,讓子類決定實例化哪個類。工廠方法使一個類的實例化延伸到其子類
- (自我總結)核心:
- 頂層工廠接口和一系列實現類
- 頂層產品接口和一系列實現類
-
優點:
- 解決了簡單工廠需要維護的
if-else 列表
(極大程度上滿足了開閉原則),選擇使用移交給調用方 - 保留了簡單工廠創建對象的隱蔽性
- 解決了簡單工廠需要維護的
-
缺點:
- 需要維護大量的額外使用工廠類,並且需要由使用方決定如果選擇(一定的)。
- 此模式相比較工廠方法類更加笨重
-
區別
- 簡單工廠模式
- 從結構層次上,工廠方法模式將簡單工廠的工廠類抽象並依賴Product的實例產生多個Product的工廠。也就是長生一個對像由原本的
Fectory --> realProduct
變成了IFectory --> realFectory --> realProduct
實現一個計算器
通過輸入 + - ,對兩個整型數字進行運算 。
一、結構圖
通過圖我們明白,我們可以看到工廠本身也被抽象化了。這樣導致對調用者來說就需要在
使用層次
知道所有的Fectory的實現類
的使用。
但對於開發者來說,就不需要維護一個龐大的if-else的對象生成列表
,但是現在添加新的功能就不能只添加Operation還需要對應的Fectory
增加了開發的壓力
二、代碼
// 調用方 不屬於工廠結構內部
public class FactoryMethodMain {
public static void main(String[] args) {
int num_a = 1;
int num_b = 1;
char char_oper = '+';
// 這裏是由使用方選擇使用對象的工廠
// 這裏就需要使用方知道幾乎所有的工廠類
OperationFectory operationFectory = new AddFectory();
// 生成對象不需要去考慮,所有工廠都用同一個接口方法
Operation operation = operationFectory.createOperation();
int return_c = operation.getResut(num_a, num_b);
System.out.println(return_c);
}
}
// Operation頂層工廠接口
public interface OperationFectory {
Operation createOperation();
}
// 加法工廠
public class AddFectory implements OperationFectory {
@Override
public Operation createOperation() {
return new AddOperation();
}
}
// 減法工廠
public class DescFectory implements OperationFectory {
@Override
public Operation createOperation() {
return new descOperation();
}
}
// Operation頂層抽象接口
public interface Operation {
// 計算抽象接口
int getResut(int num_a, int num_b);
}
// 加法計算器
public class AddOperation implements Operation {
@Override
public int getResut(int num_a, int num_b) {
return num_a + num_a;
}
}
// 減法計算器
public class descOperation implements Operation {
@Override
public int getResut(int num_a, int num_b) {
return num_a - num_b;
}
}