MST

星途 面试题库

面试题:Objective-C中工厂模式的实现方式

在Objective-C中,请阐述工厂模式的基本概念,并举例说明如何使用工厂方法创建对象。假设我们有一个基类`Shape`,以及`Circle`和`Rectangle`两个子类,使用工厂模式来创建这些形状对象。
45.2万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

工厂模式基本概念

工厂模式是一种创建型设计模式,它提供了一种创建对象的方式,将对象的创建和使用分离。通过使用工厂模式,可以将对象创建的逻辑封装在一个工厂类中,而不是在客户端代码中直接实例化对象。这样可以提高代码的可维护性和可扩展性,当需要创建新的对象类型时,只需要在工厂类中添加相应的创建逻辑,而不需要修改大量的客户端代码。

示例代码

  1. 定义基类 Shape
#import <Foundation/Foundation.h>

@interface Shape : NSObject
- (void)draw;
@end

@implementation Shape
- (void)draw {
    NSLog(@"This is a general shape.");
}
@end
  1. 定义子类 Circle
#import "Shape.h"

@interface Circle : Shape
@end

@implementation Circle
- (void)draw {
    NSLog(@"Drawing a circle.");
}
@end
  1. 定义子类 Rectangle
#import "Shape.h"

@interface Rectangle : Shape
@end

@implementation Rectangle
- (void)draw {
    NSLog(@"Drawing a rectangle.");
}
@end
  1. 定义工厂类 ShapeFactory
#import <Foundation/Foundation.h>
#import "Shape.h"
#import "Circle.h"
#import "Rectangle.h"

@interface ShapeFactory : NSObject
+ (Shape *)createShapeWithType:(NSString *)type;
@end

@implementation ShapeFactory
+ (Shape *)createShapeWithType:(NSString *)type {
    if ([type isEqualToString:@"circle"]) {
        return [[Circle alloc] init];
    } else if ([type isEqualToString:@"rectangle"]) {
        return [[Rectangle alloc] init];
    }
    return nil;
}
@end
  1. 使用工厂方法创建对象
#import <Foundation/Foundation.h>
#import "ShapeFactory.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Shape *circle = [ShapeFactory createShapeWithType:@"circle"];
        [circle draw];
        
        Shape *rectangle = [ShapeFactory createShapeWithType:@"rectangle"];
        [rectangle draw];
    }
    return 0;
}

在上述代码中,ShapeFactory 类是工厂类,它提供了一个类方法 createShapeWithType: 来根据传入的类型创建不同的形状对象。客户端代码通过调用这个工厂方法来创建 CircleRectangle 对象,而不需要关心具体的创建细节。