装饰者模式用OC实现

// 产品抽象类
@interface Product : NSObject
- (NSString *)productName;
- (CGFloat)productPrice;
@end

@implementation Product
- (NSString *)productName {
    return @"Product";
}
- (CGFloat)productPrice {
    return 0.0f;
}
@end

// 具体产品,实现产品抽象类
@interface ProductA : Product
@end

@implementation ProductA
- (NSString *)productName {
    return @"Product A";
}
- (CGFloat)productPrice {
    return 10.0f;
}
@end

// 装饰器抽象类,实现产品抽象类
@interface Decorator : Product
{
    Product *_component;
}
- (instancetype)initWithComponent:(Product *)component;
@end

@implementation Decorator
- (instancetype)initWithComponent:(Product *)component {
    self = [super init];
    if (self) {
        _component = component;
    }
    return self;
}

- (NSString *)productName {
    return _component.productName;
}
- (CGFloat)productPrice {
    return _component.productPrice;
}
@end

// 具体装饰器 A
@interface DecoratorA : Decorator
@end

@implementation DecoratorA
- (instancetype)initWithComponent:(Product *)component {
    self = [super initWithComponent:component];
    if (self) {
    }
    return self;
}

- (NSString *)productName {
    return [NSString stringWithFormat:@"%@ + AddA", self.component.productName];
}
- (CGFloat)productPrice {
    return self.component.productPrice + 2.0f;
}
@end

// 具体装饰器 B
@interface DecoratorB : Decorator
@end

@implementation DecoratorB
- (instancetype)initWithComponent:(Product *)component {
    self = [super initWithComponent:component];
    if (self) {
    }
    return self;
}

- (NSString *)productName {
    return [NSString stringWithFormat:@"%@ + AddB", self.component.productName];
}
- (CGFloat)productPrice {
    return self.component.productPrice + 5.0f;
}
@end

// 客户端代码
int main(int argc, char * argv[]) {
    @autoreleasepool {
        Product *product = [[ProductA alloc] init];
        NSLog(@"Product Name: %@, Price: %.2f", product.productName, product.productPrice);
    
        Decorator *decoratorA = [[DecoratorA alloc] initWithComponent:product];
        NSLog(@"Product Name: %@, Price: %.2f", decoratorA.productName, decoratorA.productPrice);
        
        Decorator *decoratorB = [[DecoratorB alloc] initWithComponent:decoratorA];
        NSLog(@"Product Name: %@, Price: %.2f", decoratorB.productName, decoratorB.productPrice);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值