簡單工廠模式(Simple Factory)透過物件導向的封裝、繼承與多型來降低程式碼的耦合度,把「具體類別的實例化」這件事交給一個靜態的工廠方法來執行。
這個模式包含三種角色:
工廠類(Simple Factory):只包含用來建立具體產品的靜態方法。
抽象產品(Product):定義工廠要回傳的產品型別。
具體產品(ConcreteProduct):實際的產品實作。
類圖中,客戶端與工廠類分開:消費者任何時候需要某種產品,只需向工廠請求即可,無須修改就能接納新產品。ProductA、ProductB、ProductC 都繼承自 Product,各自的 Show 方法負責自我描述;Factory 則依不同條件建立不同的 Product 物件。
需求是做一個計算器,包含加、減、乘、除四種基本運算。
- (IBAction)getResult:(id)sender {
NSString *strFirstNum = self.firstNumTextField.text;
NSString *strSecondNum = self.secondNumTextField.text;
NSString *strOperation = self.operationTextField.text;
if ([strOperation isEqualToString:@"+"]) {
double result = [strFirstNum doubleValue] + [strSecondNum doubleValue];
self.resultTextField.text = [NSString stringWithFormat:@"%f", result];
} else if ([strOperation isEqualToString:@"-"]) {
double result = [strFirstNum doubleValue] - [strSecondNum doubleValue];
self.resultTextField.text = [NSString stringWithFormat:@"%f", result];
} else if ([strOperation isEqualToString:@"*"]) {
double result = [strFirstNum doubleValue] * [strSecondNum doubleValue];
self.resultTextField.text = [NSString stringWithFormat:@"%f", result];
} else if ([strOperation isEqualToString:@"/"]) {
// 除數不能為 0
if ([strSecondNum isEqualToString:@"0"]) {
UIAlertView *tempAlert = [[UIAlertView alloc] initWithTitle:@"警告"
message:@"除數不能為 0"
delegate:nil
cancelButtonTitle:@"取消"
otherButtonTitles:nil];
[tempAlert show];
} else {
double result = [strFirstNum doubleValue] / [strSecondNum doubleValue];
self.resultTextField.text = [NSString stringWithFormat:@"%f", result];
}
}
}
功能上確實能跑,但問題很明顯:如果之後要加入開平方、乘方,就得再插入一個 else if;如果要加一百種運算呢?每次擴充都要改這段程式碼,完全違反可擴充性原則。
解法是把「運算」抽象出來,再加入一個運算工廠負責接收使用者輸入的操作符。
#import <Foundation/Foundation.h> /*! 操作方法協議介面 */ @protocol OperationProtocol <NSObject> - (double)getResult; @end
#import <Foundation/Foundation.h> #import "OperationProtocol.h" /*! 操作方法父類 */ @interface Operation : NSObject <OperationProtocol> @property (nonatomic, assign) double firstNum; // 第一個運算元 @property (nonatomic, assign) double secondNum; // 第二個運算元 @end
#import "Operation.h" /*! 加法實作類 */ @interface OperationAdd : Operation @end
#import "OperationAdd.h"
@implementation OperationAdd
- (double)getResult {
return self.firstNum + self.secondNum;
}
@end
減法、乘法、除法依此類推,除法類別可在 getResult 中自行處理除數為 0 的情況(例如回傳 NAN 或拋出錯誤),不必讓 caller 費心。
#import <Foundation/Foundation.h> #import "Operation.h" /*! 操作工廠類 */ @interface OperationFactory : NSObject + (Operation *)createOperate:(NSString *)operateStr; @end
#import "OperationFactory.h"
#import "OperationAdd.h"
#import "OperationSub.h"
#import "OperationMultiply.h"
#import "OperationDivide.h"
@implementation OperationFactory
+ (Operation *)createOperate:(NSString *)operateStr {
Operation *oper = nil;
if ([operateStr isEqualToString:@"+"]) {
oper = [[OperationAdd alloc] init];
} else if ([operateStr isEqualToString:@"-"]) {
oper = [[OperationSub alloc] init];
} else if ([operateStr isEqualToString:@"*"]) {
oper = [[OperationMultiply alloc] init];
} else if ([operateStr isEqualToString:@"/"]) {
oper = [[OperationDivide alloc] init];
}
return oper;
}
@end
- (IBAction)clickingOperation:(id)sender {
NSString *strFirstNum = self.firstNumTextField.text;
NSString *strSecondNum = self.secondNumTextField.text;
Operation *oper = [OperationFactory createOperate:self.operationTextField.text];
oper.firstNum = [strFirstNum doubleValue];
oper.secondNum = [strSecondNum doubleValue];
self.resultTextField.text = [NSString stringWithFormat:@"%f", [oper getResult]];
}
客戶端完全不需要知道運算的具體實作細節,只負責「消費」物件。此後若要新增運算,只需繼承 Operation、實作 getResult,並在工廠裡多一個判斷分支即可——做到「對擴展開放、對修改關閉」。
職責單一、實作簡單,且實現了客戶端程式碼與具體實作之間的解耦。工廠類是整個模式的關鍵,它包含必要的邏輯判斷,依外界給定的資訊決定建立哪個具體類別的物件。使用工廠類之後,外界可以從「直接 new 具體物件」的尷尬局面中解脫出來,只需要負責消費,不必關心物件如何建立與組織,各自的職責與權利也更明確,有助於整體架構的優化。
工廠類集中了所有實例的建立邏輯,違反高內聚的責任分配原則;它能建立的類別只能是事先考慮到的,若要新增類別就必須修改工廠類本身,因此違背開放封閉原則。當具體產品類別不斷增多時,工廠類裡的條件判斷會越來越複雜,這種「條件判斷」與「產品型別判斷」交錯在一起的情況,很難避免模組功能蔓延,對維護與擴充都不利。這些缺點在後續的「工廠方法模式」中得到了部分克服——把工廠本身也抽象化,讓每個具體工廠負責建立對應的產品。
工廠類負責建立的物件數量不多;客戶端只知道傳入參數,對於建立邏輯並不關心。由於簡單工廠容易違反高內聚原則,一般只在情況相對簡單時使用。
相較於 Java,Objective-C 有兩個更地道的寫法可以取代工廠類裡的 if-else 串:
一是用字典查表。把 @{@"+": [OperationAdd class], @"-": [OperationSub class]} 定義成靜態字典,再透過 objectForKey: 取出 Class 並 alloc,新增運算時只需加一筆字典項目,不必改動任何邏輯程式碼。
二是用 Class 的 performSelector 或直接使用 IMP。若運算本身可以表示成一個 C 函式,也可以把 IMP 存進字典直接呼叫,效能更好,但會犧牲一些物件導向的彈性。
學習的路上,與君共勉。