面试题答案
一键面试#import <Foundation/Foundation.h>
// 基础图形类
@interface Shape : NSObject
- (void)draw;
@end
@implementation Shape
- (void)draw {
NSLog(@"绘制图形");
}
@end
// 装饰器基类,继承自Shape
@interface ShapeDecorator : Shape
@property (nonatomic, strong) Shape *decoratedShape;
- (instancetype)initWithShape:(Shape *)shape;
@end
@implementation ShapeDecorator
- (instancetype)initWithShape:(Shape *)shape {
self = [super init];
if (self) {
_decoratedShape = shape;
}
return self;
}
- (void)draw {
[self.decoratedShape draw];
}
@end
// 颜色装饰器
@interface ColorDecorator : ShapeDecorator
@property (nonatomic, strong) NSString *color;
- (instancetype)initWithShape:(Shape *)shape color:(NSString *)color;
@end
@implementation ColorDecorator
- (instancetype)initWithShape:(Shape *)shape color:(NSString *)color {
self = [super initWithShape:shape];
if (self) {
_color = color;
}
return self;
}
- (void)draw {
[super draw];
NSLog(@"添加颜色: %@", self.color);
}
@end
// 尺寸装饰器
@interface SizeDecorator : ShapeDecorator
@property (nonatomic, assign) CGFloat size;
- (instancetype)initWithShape:(Shape *)shape size:(CGFloat)size;
@end
@implementation SizeDecorator
- (instancetype)initWithShape:(Shape *)shape size:(CGFloat)size {
self = [super initWithShape:shape];
if (self) {
_size = size;
}
return self;
}
- (void)draw {
[super draw];
NSLog(@"添加尺寸: %.2f", self.size);
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 创建一个基础图形
Shape *basicShape = [[Shape alloc] init];
// 用颜色装饰图形
ColorDecorator *coloredShape = [[ColorDecorator alloc] initWithShape:basicShape color:@"红色"];
// 用尺寸装饰已经有颜色的图形
SizeDecorator *coloredAndSizedShape = [[SizeDecorator alloc] initWithShape:coloredShape size:10.5];
[basicShape draw];
[coloredShape draw];
[coloredAndSizedShape draw];
}
return 0;
}
上述代码首先定义了基础的Shape
类,然后通过ShapeDecorator
作为装饰器基类,派生出ColorDecorator
和SizeDecorator
两个具体的装饰器类,分别为图形添加颜色和尺寸属性。在main
函数中展示了如何通过装饰器模式动态地为Shape
对象添加不同的装饰。