定义
不改变原类和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象
场景
- 需要动态的给对象增加功能
- 给对象增加功能,但又不想通过继承的方式
实现
以泡咖啡为例,用户需要先加糖再加牛奶,或者先加牛奶再加糖,这种方式就非常适合使用装饰器模式,如果使用继承方式,将会导致类非常多,很混乱。
1、UML图

decorator.png
2、使用
- 构建协议,规范操作
@protocol CoffeeProtocol <NSObject>
-(void)makeCoffee;
@end
- 构建装饰器基类
该类持有实现CoffeeProtocol的对象。
#import "CoffeeProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface CoffeeDecorator : NSObject<CoffeeProtocol>
@property(nonatomic,readonly,strong)id<CoffeeProtocol> coffee;
-(instancetype)initWithDecorator:(id<CoffeeProtocol>)coffee;
@end
#import "CoffeeDecorator.h"
@implementation CoffeeDecorator
- (instancetype)initWithDecorator:(id<CoffeeProtocol>)coffee
{
self = [super init];
if (self) {
_coffee = coffee;
}
return self;
}
- (void)makeCoffee{
if(self.coffee){
[self.coffee makeCoffee];
}
}
@end
- 构建具体的装饰器
@interface SugarCoffee : CoffeeDecorator
@end
#import "SugarCoffee.h"
@implementation SugarCoffee
- (void)makeCoffee{
[super makeCoffee];
NSLog(@"加糖");
}
@end
@interface MilkCoffee : CoffeeDecorator
@end
#import "MilkCoffee.h"
@implementation MilkCoffee
- (void)makeCoffee{
[super makeCoffee];
NSLog(@"牛奶");
}
@end
- 被装饰的对象
@interface OriginalCoffee : NSObject<CoffeeProtocol>
@end
#import "OriginalCoffee.h"
@implementation OriginalCoffee
- (void)makeCoffee{
NSLog(@"原味咖啡");
}
@end
- Client调用
OriginalCoffee *originalCoffee = [[OriginalCoffee alloc] init];
//加奶再加糖
MilkCoffee *milk = [[MilkCoffee alloc] initWithDecorator:originalCoffee];
SugarCoffee *sugar = [[SugarCoffee alloc] initWithDecorator:milk];
[sugar makeCoffee];
NSLog(@"-------------");
//加糖再加奶
SugarCoffee *sugar1 = [[SugarCoffee alloc] initWithDecorator:originalCoffee];
MilkCoffee *milk1 = [[MilkCoffee alloc] initWithDecorator:sugar1];
[milk1 makeCoffee];
}
总结
可以提供比继承更灵活的方式去扩展对象的功能,通过排列组合,可以对对象做动态的功能扩展。
代码
链接: https://pan.baidu.com/s/1yIiUBBVpi5p4fJvNh9LpjQ 提取码: fg73