// 产品抽象类
@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;
}
装饰者模式用OC实现
最新推荐文章于 2024-10-08 16:44:01 发布