MST

星途 面试题库

面试题:Objective-C装饰器模式在复杂业务场景中的应用

在一个iOS应用开发场景中,有一个文本显示组件TextView,它有基本的显示功能。现在要求通过装饰器模式实现多种功能扩展,如添加滚动条、添加文本加密显示、添加字数统计。请详细描述你的设计思路,并给出关键的Objective-C代码片段。
41.4万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义基础组件协议:定义一个协议,规定文本显示组件的基本行为,例如显示文本。
  2. 实现基础组件:创建一个遵守上述协议的基础TextView类,实现基本的文本显示功能。
  3. 定义装饰器抽象类:创建一个抽象的装饰器类,它同样遵守基础组件协议,并且持有一个基础组件的实例。
  4. 实现具体装饰器:分别创建用于添加滚动条、文本加密显示、字数统计功能的具体装饰器类,它们继承自抽象装饰器类,在实现协议方法时,调用基础组件实例的方法,并添加各自的功能。

关键Objective - C代码片段

  1. 基础组件协议
@protocol TextDisplayComponent <NSObject>
- (void)displayText:(NSString *)text;
@end
  1. 基础TextView类
@interface TextView : NSObject <TextDisplayComponent>
- (void)displayText:(NSString *)text {
    NSLog(@"显示文本: %@", text);
}
@end
  1. 抽象装饰器类
@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
  1. 滚动条装饰器
@interface ScrollBarDecorator : TextDisplayDecorator
- (void)displayText:(NSString *)text {
    [super displayText:text];
    NSLog(@"添加滚动条");
}
@end
  1. 文本加密装饰器
@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
  1. 字数统计装饰器
@interface WordCountDecorator : TextDisplayDecorator
- (void)displayText:(NSString *)text {
    [super displayText:text];
    NSLog(@"字数统计: %lu", (unsigned long)text.length);
}
@end
  1. 使用示例
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!"];