工厂模式基本组成部分
- 产品(Product):定义工厂创建对象的接口,具体产品是实现该接口的类。在图形对象示例中,图形类就是产品,圆形、矩形类是具体产品。
- 具体产品(Concrete Product):实现产品接口的具体类,如圆形类、矩形类。
- 工厂(Creator):声明创建产品对象的工厂方法,该方法返回产品类型。具体工厂类实现此方法来创建具体产品对象。
代码示例
- 定义图形协议(产品接口)
@protocol Shape <NSObject>
- (void)draw;
@end
- 圆形类(具体产品)
#import <Foundation/Foundation.h>
#import "Shape.h"
@interface Circle : NSObject <Shape>
@end
@implementation Circle
- (void)draw {
NSLog(@"绘制圆形");
}
@end
- 矩形类(具体产品)
#import <Foundation/Foundation.h>
#import "Shape.h"
@interface Rectangle : NSObject <Shape>
@end
@implementation Rectangle
- (void)draw {
NSLog(@"绘制矩形");
}
@end
- 图形工厂类(工厂)
#import <Foundation/Foundation.h>
#import "Shape.h"
#import "Circle.h"
#import "Rectangle.h"
@interface ShapeFactory : NSObject
+ (id<Shape>)shapeWithType:(NSString *)type;
@end
@implementation ShapeFactory
+ (id<Shape>)shapeWithType:(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 {
id<Shape> circle = [ShapeFactory shapeWithType:@"circle"];
[circle draw];
id<Shape> rectangle = [ShapeFactory shapeWithType:@"rectangle"];
[rectangle draw];
}
return 0;
}