最近公司的工作还比较轻松,自己想去写一些东西,因为本人是做ios开发的,能够希望在这个行业能够结交更多地朋友,下面是本人对一些常用的开发模式,小例子都是去采用的OC语言,希望大家能够提出观点,咱们多多去交流.
下面这个小案例就是简单工厂模式:
简单工厂模式:
(1)计算器小例子
#########
// 计算器的类
#import <Foundation/Foundation.h>
@interface Calutor : NSObject
{
float _num1;
float _num2;
}
@property float num1;
@property float num2;
- (float)getResult;
@end
#import "Calutor.h"
@implementation Calutor
- (float)getResult{
float result=0;
return result;
}
@end
##########
#import "Calutor.h"
@interface Plus : Calutor
@end
#import "Plus.h"
// 加法类
@implementation Plus
- (float)getResult{
float rel=0;
rel= self.num1+self.num2;
return rel;
}
@end
########
// 减法的类
#import "Calutor.h"
@interface Jian : Calutor
@end
#import "Jian.h"
@implementation Jian
- (float)getResult{
float rel=0;
rel=_num1+_num2;
return rel;
}
@end
########
#import "Calutor.h"
@interface Mul : Calutor
@end
#import "Mul.h"
@implementation Mul
- (float)getResult{
float rel=0;
rel=_num1*_num2;
return rel;
}
@end
#######
#import "Calutor.h"
@interface Div : Calutor
@end
#import "Div.h"
@implementation Div
- (float)getResult{
float rel=0;
rel=_num1/_num2;
return rel;
}
@end
######
// 计算器的工厂类
#import <Foundation/Foundation.h>
#import "Jian.h"
#import "Plus.h"
#import "Mul.h"
#import "Div.h"
@interface CalutorFactory : NSObject
+ (Calutor*)createOperate:(char)c;
@end
#import "CalutorFactory.h"
@implementation CalutorFactory
+ (Calutor*)createOperate:(char)c{
Calutor *cal=nil;
switch (c) {
case ‘+‘:
cal=[Plus new];
break;
case ‘-‘:
cal=[Jian new];
break;
case ‘*‘:
cal=[Mul new];
break;
case ‘/‘:
cal=[Div new];
break;
default:
cal=nil;
break;
}
return cal;
}
@end
#######
#import <Foundation/Foundation.h>
#import "CalutorFactory.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Calutor*cal;
cal=[CalutorFactory createOperate:‘+‘];
cal.num1=2;
cal.num2=3;
printf("%.2f\n",[cal getResult]);
} return 0;
}
因为OC是一门动态的语言,对于面向的对象的一些特性表现得更加明显,上面的小案例就是简单工厂模式.
谢谢.