设计思路
- 定义基础组件协议:定义一个协议,规定文本显示组件的基本行为,例如显示文本。
- 实现基础组件:创建一个遵守上述协议的基础TextView类,实现基本的文本显示功能。
- 定义装饰器抽象类:创建一个抽象的装饰器类,它同样遵守基础组件协议,并且持有一个基础组件的实例。
- 实现具体装饰器:分别创建用于添加滚动条、文本加密显示、字数统计功能的具体装饰器类,它们继承自抽象装饰器类,在实现协议方法时,调用基础组件实例的方法,并添加各自的功能。
关键Objective - C代码片段
- 基础组件协议
@protocol TextDisplayComponent <NSObject>
- (void)displayText:(NSString *)text;
@end
- 基础TextView类
@interface TextView : NSObject <TextDisplayComponent>
- (void)displayText:(NSString *)text {
NSLog(@"显示文本: %@", text);
}
@end
- 抽象装饰器类
@interface TextDisplayDecorator : NSObject <TextDisplayComponent>
@property (nonatomic, strong) id<TextDisplayComponent> component;
- (instancetype)initWithComponent:(id<TextDisplayComponent>)component;
@end
@implementation TextDisplayDecorator
- (instancetype)initWithComponent:(id<TextDisplayComponent>)component {
self = [super init];
if (self) {
_component = component;
}
return self;
}
- (void)displayText:(NSString *)text {
[self.component displayText:text];
}
@end
- 滚动条装饰器
@interface ScrollBarDecorator : TextDisplayDecorator
- (void)displayText:(NSString *)text {
[super displayText:text];
NSLog(@"添加滚动条");
}
@end
- 文本加密装饰器
@interface EncryptionDecorator : TextDisplayDecorator
- (NSString *)encryptText:(NSString *)text {
// 简单示例,实际加密算法会更复杂
NSMutableString *encryptedText = [NSMutableString string];
for (NSUInteger i = 0; i < text.length; i++) {
unichar c = [text characterAtIndex:i];
[encryptedText appendFormat:@"*"];
}
return encryptedText;
}
- (void)displayText:(NSString *)text {
NSString *encrypted = [self encryptText:text];
[super displayText:encrypted];
NSLog(@"添加文本加密显示");
}
@end
- 字数统计装饰器
@interface WordCountDecorator : TextDisplayDecorator
- (void)displayText:(NSString *)text {
[super displayText:text];
NSLog(@"字数统计: %lu", (unsigned long)text.length);
}
@end
- 使用示例
TextView *textView = [[TextView alloc] init];
ScrollBarDecorator *scrollBarDecorator = [[ScrollBarDecorator alloc] initWithComponent:textView];
EncryptionDecorator *encryptionDecorator = [[EncryptionDecorator alloc] initWithComponent:scrollBarDecorator];
WordCountDecorator *wordCountDecorator = [[WordCountDecorator alloc] initWithComponent:encryptionDecorator];
[wordCountDecorator displayText:@"Hello, World!"];