簡單工廠模式
-
介紹
- 結構圖:
(自我總結)核心: 工廠類(判斷生成對象)和頂層抽象類(用於管理一系列的實現類)
- 結構圖:
-
優點:
- 添加對應類的方式可以通過添加類+修改工廠的判斷列表的形式
- 提高代碼可複用的效果
- 代碼調用方不需要指導頂層抽象的類的所有子類,只需要提供滿足工廠的格式和方法即可
-
缺點:
- 不夠滿足開閉-原則(拓展時,要儘量避免源碼的修改)
- 由於是類級別的,有些笨重。面對經常發生變化的情況或是僅僅是方法層次不易使用
實現一個計算器
通過輸入 + - ,對兩個整型數字進行運算 。
一、結構圖
通過圖我們明白,當我們把計算工廠封裝完畢之後。其他調用的開發人員只需要知道Factory的API和Operation的計算方法即可,對於背後的邏輯不必瞭解。
二、代碼
// 調用方 不屬於工廠結構內部
public class SimpleFectoryMain {
public static void main(String[] args) {
// 定義初始數據
int num_a = 1;
int num_b = 0;
// 可以自由修改
char char_opertion = '+';
// 創建工廠並獲取operation對象 隱藏了operation的創建過程
// 用戶只需要知道createOperation以及getResut的使用即可
OperationFectory fectory = new OperationFectory();
Operation operation = fectory.createOperation(char_opertion);
// 使用對象得出結論
int result = operation.getResut(num_a, num_b);
System.out.println(result);
}
}
// Operation工廠類
public class OperationFectory {
// 創建Operation對象
Operation createOperation(char oper){
// Operation對象選擇生成器
switch (oper){
case '+' : return new AddOperation();
case '-' : return new descOperation();
default:
try {
throw new Exception("該計算形式不合法");
} catch (Exception e) {
e.printStackTrace();
};
}
return null;
}
}
// 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;
}
}