MST

星途 面试题库

面试题:Objective-C中享元模式的基本实现步骤

请描述在Objective-C中实现享元模式的基本步骤,并且举例说明在一个简单的图形绘制应用场景里如何运用享元模式,假设该应用需要绘制大量的圆形和矩形。
11.7万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

1. 享元模式实现基本步骤

  1. 定义享元类
    • 包含内部状态(即对象中不会随外部环境改变而改变的部分,可共享)。
    • 通常有一个方法来操作这些内部状态,并根据需要结合外部状态(随环境改变的部分)进行相应处理。
  2. 定义享元工厂类
    • 负责创建和管理享元对象。
    • 一般使用一个集合(如字典)来存储已创建的享元对象,当请求一个享元对象时,先从集合中查找,如果存在则返回,否则创建并添加到集合中再返回。
  3. 客户端使用
    • 客户端向享元工厂请求享元对象,通过传入必要的内部状态信息,然后结合外部状态使用享元对象。

2. 图形绘制应用场景举例

  1. 定义图形享元类
// 抽象图形享元类
@interface Shape : NSObject
@property (nonatomic, strong) NSString *color;
- (void)draw;
@end

@implementation Shape
- (void)draw {
    NSLog(@"未实现具体绘制逻辑");
}
@end

// 圆形享元类
@interface Circle : Shape
@end

@implementation Circle
- (void)draw {
    NSLog(@"绘制颜色为 %@ 的圆形", self.color);
}
@end

// 矩形享元类
@interface Rectangle : Shape
@end

@implementation Rectangle
- (void)draw {
    NSLog(@"绘制颜色为 %@ 的矩形", self.color);
}
@end
  1. 定义享元工厂类
@interface ShapeFactory : NSObject
+ (instancetype)sharedFactory;
- (Shape *)getShapeWithColor:(NSString *)color andType:(NSString *)type;
@end

@implementation ShapeFactory
static ShapeFactory *sharedFactory = nil;
+ (instancetype)sharedFactory {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedFactory = [[self alloc] init];
    });
    return sharedFactory;
}

- (NSMutableDictionary<NSString *, Shape *> *)shapePool {
    static NSMutableDictionary<NSString *, Shape *> *pool = nil;
    if (!pool) {
        pool = [NSMutableDictionary dictionary];
    }
    return pool;
}

- (Shape *)getShapeWithColor:(NSString *)color andType:(NSString *)type {
    NSString *key = [NSString stringWithFormat:@"%@-%@", type, color];
    Shape *shape = self.shapePool[key];
    if (!shape) {
        if ([type isEqualToString:@"circle"]) {
            shape = [[Circle alloc] init];
        } else if ([type isEqualToString:@"rectangle"]) {
            shape = [[Rectangle alloc] init];
        }
        shape.color = color;
        self.shapePool[key] = shape;
    }
    return shape;
}
@end
  1. 客户端使用
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ShapeFactory *factory = [ShapeFactory sharedFactory];
        Shape *redCircle = [factory getShapeWithColor:@"red" andType:@"circle"];
        [redCircle draw];
        Shape *blueRectangle = [factory getShapeWithColor:@"blue" andType:@"rectangle"];
        [blueRectangle draw];
        // 再次获取相同颜色和类型的图形,会从工厂的池中获取已创建的对象
        Shape *anotherRedCircle = [factory getShapeWithColor:@"red" andType:@"circle"];
        [anotherRedCircle draw];
    }
    return 0;
}

在上述代码中,通过享元模式,对于相同颜色的圆形或矩形,不会重复创建新的对象,而是从享元工厂的对象池中获取已创建的对象,从而节省内存,提高性能,尤其适用于需要绘制大量图形的场景。