簡單工廠學習的小例子

簡單工廠模式(Simple Factory Pattern)屬於類的創新型模式,又叫靜態工廠方法模式(Static FactoryMethod Pattern),是經過專門定義一個類來負責建立其餘類的實例,被建立的實例一般都具備共同的父類。atom

下面的例子是一個實現基本四則運算的計算器.spa

1.涉及的類目錄code

分別對應+,-,*,/和一個工廠類blog

 

2.實現的細節繼承

父類Operationit

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Operation : NSObject
 4 @property (nonatomic,assign) float numA;
 5 @property (nonatomic,assign) float numB;
 6 - (float)result;
 7 @end
 8 
 9 
10 #import "Operation.h"
11 
12 @implementation Operation
13 - (float)result
14 {
15     return 0;
16 }
17 @end

有兩個數和一個獲取結果的方法io

 

一下的類都是繼承了Operation類,並重寫了result方法class

加.import

#import "OperationAdd.h"

@implementation OperationAdd
- (float)result
{
    return self.numA + self.numB;
}
@end

  減.float

1 #import "OperationSub.h"
2 
3 @implementation OperationSub
4 - (float)result
5 {
6     return self.numA - self.numB;
7 }
8 @end

乘.

1 #import "OperationMul.h"
2 
3 @implementation OperationMul
4 - (float)result
5 {
6     return self.numA * self.numB;
7 }
8 @end

1 #import "OperationDiv.h"
2 
3 @implementation OperationDiv
4 - (float)result
5 {
6     NSAssert(0 != self.numB, @"除數不能爲0");
7     return self.numA / self.numB;
8 }
9 @end

 

工廠類的實現

 1 #import "Operation.h"
 2 
 3 @interface OperationFactory : NSObject
 4 + (Operation*)createOperation:(char)symbol;
 5 @end
 6 
 7 #import "OperationFactory.h"
 8 #import "OperationAdd.h"
 9 #import "OperationSub.h"
10 #import "OperationMul.h"
11 #import "OperationDiv.h"
12 @implementation OperationFactory
13 + (Operation *)createOperation:(char)symbol
14 {
15     Operation *operation;
16     switch (symbol) {
17         case '+':
18             operation = [[OperationAdd alloc]init];
19             break;
20         case '-':
21             operation = [[OperationSub alloc]init];
22         case '*':
23             operation = [[Operation alloc]init];
24         case '/':
25             operation = [[OperationDiv alloc]init];
26         default:
27             break;
28     }
29     
30     return operation;
31 }
32 @end

主要是一個根據輸入的運算操做符建立響應的運算計算結果的方法:

createOperation:

應用

 1 #import <Foundation/Foundation.h>
 2 #import "OperationFactory.h"
 3 int main(int argc, const char * argv[]) {
 4     @autoreleasepool {
 5         Operation *operation = [OperationFactory createOperation:'/' ];
 6         operation.numA = 10.0;
 7         operation.numB = 2;
 8     
 9         NSLog(@"div result = %f",[operation result]);
10         
11          operation = [OperationFactory createOperation:'+'];
12         operation.numA = 10.0;
13         operation.numB = 2;
14         NSLog(@"add result = %f",[operation result]);
15     
16     }
17     return 0;
18 }

結果

2016-01-18 09:25:38.778 FactoryModel[719:28322] div result = 5.000000

2016-01-18 09:25:38.779 FactoryModel[719:28322] add result = 12.000000

相關文章
相關標籤/搜索