結(jié)構(gòu)型之四-裝飾模式

Decrator(裝飾模式)

動(dòng)態(tài)的給一個(gè)對象添加一些額外的職責(zé),就增加功能來說,裝飾模式比生成子類更加靈活。decorate應(yīng)該像禮物一樣層層封裝,每一層都添加新的功能。

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添加的裝飾功能,相當(dāng)于對Component進(jìn)行裝飾");
}
@end

設(shè)計(jì)圖

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容