Obj-C 实现设计模式 -- 装饰
装饰模式,个人觉得没有太多让人眼前一亮的东西,也或许是现在理解的太过肤浅。
子类通过继承父类对父类(或者接口)进行装饰,改变父类的一些属性,丰富并装饰父类的一些方法。
不多说,贴一贴代码吧。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@interface Beverage : NSObject { NSString * _description; } - (id) init; @property (nonatomic, retain) NSString * description; - (float) cost; - (NSString *) getDescription; @end
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
- (id) init{ self = [super init]; if (self) { _description = @"Beverage"; } return self; } - (float) cost{ return 0.0; } - (NSString *) getDescription{ return @"Beverage"; }
贴一个子类吧。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@interface Mocha : Beverage { Beverage * _beverage; } -(id) initWithBverage:(Beverage *) beverage; - (NSString *) getDescription; - (float) cost; @end
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@implementation Mocha -(id) initWithBverage:(Beverage *) beverage{ self = [super init]; if (self) { _beverage = beverage; } return self; } - (NSString *) getDescription{ return [[_beverage getDescription] stringByAppendingString:@", Mocha"]; } - (float) cost{ return 0.80+[_beverage cost]; } @end
循环调用进行装饰这块还是蛮精彩的。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Beverage * beverage = [[Espresso alloc] init]; NSLog(@"%@ and %f",[beverage description],[beverage cost]); beverage = [[Mocha alloc] initWithBverage:beverage]; beverage = [[Mocha alloc] initWithBverage:beverage]; NSLog(@"%@ and %f",[beverage getDescription],[beverage cost]);