iOS 之设计模式
一个咖啡店卖好几种咖啡:摩卡,布列夫,拿铁等等 咖啡有很多搭配:方糖,鲜牛奶,奶油,盐等. 试设计计算出咖啡(+搭配)的单价模型.
虚基类 Coffee
这个类包含什么呢 { . 咖啡的单价(不含 方糖 奶等 调味料) -->price . 一个存放调味料的容器 -->ecoratorRelishChain . 一个可以得到总价的方法 --> getTotalPrices }
咖啡类都继承自该类:
h文件
//abstract 咖啡基类
@class DecoratorChain;
@interface Coffee: NSObject
@property ( nonatomic,strong ) DecoratorChain *ecoratorRelishChain;//用来存储 奶 方糖 等等的调料 可以把它想象成一个调味盒
@property ( nonatomic,strong ) NSDecimalNumber *price;//单价 不含配料
-(NSDecimalNumber *) getTotalPrices;//得到总价
@end
m 文件
@interface Coffee()
@property(nonatomic,strong) NSString * _coffeeName;
@end
@implementation Coffee
- (id)init
{
self = [super init];
if (self) {
_coffeeName=@"咖啡名称";
price = [[NSDecimalNumber alloc] initWithString:@"20"];
}
return self;
}
-(NSDecimalNumber *)getTotalPrices
{
return [self.price decimalNumberByAdding: [ecoratorRelishChain getCountPrice]];
}
@end
虚基类 ECoratorRelish
EcoratorRelish 是 方糖 奶油 牛奶 盐 等等的抽象类 这个继承在button 点击的时候 可以自动将自己加入到chain (调料盘中)
这个类包含什么呢 { . 自身的单价 -->price . 可以修改价钱的策略 --> configPrivilege }
h 文件
@interface EcoratorRelish: UIButton
@property(nonatomic,strong) NSDecimalNumber *price;//单价
//Overload
-(void)configPrivilege;//可以配置优惠策略
-(DecoratorChain *)getComponentCoffee;
@end
m 文件
@implementation EcoratorRelish
@synthesize price;
- (id)init
{
self = [super init];
if (self) {
[self addTarget:self action:@selector(addDecoratorChain) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
//Overload
-(void)configPrivilege
{
//可以配置优惠策略
}
//获取当前的辅料坐在的ViewController
- (UIViewController *)getViewController {
Class vcc = [UIViewController class];
UIResponder *responder = self;
while ((responder = [responder nextResponder]))
if ([responder isKindOfClass: vcc])
return (UIViewController *)responder;
return nil;
}
//获取要装饰的咖啡的调味盒(chain)
-(DecoratorChain *)getEcoratorRelishChain
{
return [self getViewController].coffee.ecoratorRelishChain;
}
//将自己加到咖啡的调味盒(chain)
-(void)addDecoratorChain
{
[[self getEcoratorRelishChain] addDecoratorRelish:self];
}
@end
调料盒DecoratorChain
h 文件
//用于保存配料的chain
@interface DecoratorChain: NSMutableArray
-(void)addDecoratorRelish:(EcoratorRelish*)ecoratorRelish;
@end
m文件
@interface DecoratorChain()
@property(nonatomic,strong) NSDecimalNumber * _countPrice;
@end
@implementation DecoratorChain
@synthesize _countPrice;
- (id)init
{
self = [super init];
if (self) {
_countPrice = [[NSDecimalNumber alloc]init];
}
return self;
}
-(void)addDecoratorRelish:(EcoratorRelish*)ecoratorRelish
{
[self addObject:ecoratorRelish];
}
//得到当前所有chain 里面的总价
-(NSDecimalNumber*)getCountPrice
{
for (EcoratorRelish *tmp in self ) {
[_countPrice decimalNumberByAdding:tmp.price];
}
return _countPrice;
}
@end