Decrator(装饰模式)
动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。decorate应该像礼物一样层层封装,每一层都添加新的功能。
VC.m
- (void)viewDidLoad {
[super viewDidLoad];
//原始对象
ConcreteComponent *component = [[ConcreteComponent alloc]init];
//装饰对象
ConcreteDecoratorA *decoratorA = [[ConcreteDecoratorA alloc]init];
ConcreteDecoratorB *decoratorB = [[ConcreteDecoratorB alloc]init];
//装饰对象指定原始对象,后面就是用装饰对象。这样既有原始对象的功能,也有装饰对象的功能。
decoratorA.component = component;
decoratorB.component = component;
[decoratorA operation];
[decoratorB operation];
}
Decorator.h // 装饰类
@interface Decorator : Component
//装饰对象需要装饰的原始对象
@property(nonatomic, strong)Component *component;
@end
Decorator.m
@implementation Decorator
-(void)operation{
if (self.component) {
[self.component operation];
}
}
@end
ConcreteDecoratorA.h // 装饰者A
@interface ConcreteDecoratorA : Decorator
@end
ConcreteDecoratorA.m
@implementation ConcreteDecoratorA
-(void)operation{
[super operation];
[self addedBehavior]; // 添加的装饰功能
}
- (void)addedBehavior{
NSLog(@"ConcreteDecoratorA添加的装饰功能,相当于对Component进行装饰");
}
@end