Decrator(裝飾模式)
動態(tài)的給一個對象添加一些額外的職責肝劲,就增加功能來說葵蒂,裝飾模式比生成子類更加靈活梁沧。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