面试题答案
一键面试工厂模式基本概念
工厂模式是一种创建型设计模式,它提供了一种创建对象的方式,将对象的创建和使用分离。通过使用工厂模式,可以将对象创建的逻辑封装在一个工厂类中,而不是在客户端代码中直接实例化对象。这样可以提高代码的可维护性和可扩展性,当需要创建新的对象类型时,只需要在工厂类中添加相应的创建逻辑,而不需要修改大量的客户端代码。
示例代码
- 定义基类
Shape
#import <Foundation/Foundation.h>
@interface Shape : NSObject
- (void)draw;
@end
@implementation Shape
- (void)draw {
NSLog(@"This is a general shape.");
}
@end
- 定义子类
Circle
#import "Shape.h"
@interface Circle : Shape
@end
@implementation Circle
- (void)draw {
NSLog(@"Drawing a circle.");
}
@end
- 定义子类
Rectangle
#import "Shape.h"
@interface Rectangle : Shape
@end
@implementation Rectangle
- (void)draw {
NSLog(@"Drawing a rectangle.");
}
@end
- 定义工厂类
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
- 使用工厂方法创建对象
#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:
来根据传入的类型创建不同的形状对象。客户端代码通过调用这个工厂方法来创建 Circle
和 Rectangle
对象,而不需要关心具体的创建细节。