简单工厂模式(Simple Factory Pattern)属于类的创新型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern),是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
下面的例子是一个实现基本四则运算的计算器.
1.涉及的类目录
分别对应+,-,*,/和一个工厂类
2.实现的细节
父类Operation
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
有两个数和一个获取结果的方法
一下的类都是继承了Operation类,并重写了result方法
加.
#import "OperationAdd.h"
@implementation OperationAdd
- (float)result
{
return self.numA + self.numB;
}
@end
减.
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