
//Prototype
@protocol Shape <NSObject>
@property (nonatomic, copy) NSString *color;
- (id<Shape>)clone;
@end
//ConcretePrototype
@interface Square : NSObject <Shape>
- (instancetype)initWithColor:(NSString *)color;
@end
@implementation Square
//@synthesize is needed: the property comes from the protocol,
//not from @interface
@synthesize color;
- (instancetype)initWithColor:(NSString *)value {
self = [super init];
if (self) {
color = [value copy];
}
return self;
}
- (id<Shape>)clone {
return [[Square alloc] initWithColor:color];
}
@end
//Client
@interface ShapeMaker : NSObject
- (instancetype)initWithShape:(id<Shape>)shape;
- (id<Shape>)makeShape;
@end
@implementation ShapeMaker {
id<Shape> _shape;
}
- (instancetype)initWithShape:(id<Shape>)shape {
self = [super init];
if (self) {
_shape = shape;
}
return self;
}
- (id<Shape>)makeShape {
return [_shape clone];
}
@end
Square *square = [[Square alloc] initWithColor:@"Red"];
ShapeMaker *maker = [[ShapeMaker alloc] initWithShape:square];
id<Shape> square1 = [maker makeShape];
Square *square2 = (Square *)[maker makeShape];
NSLog(@"%@", square1.color);
NSLog(@"%@", square2.color);
| Specify the kinds of objects to create using a prototypical instance, and create new objectsby copying this prototype. |