创建父类:Cookie
创建类: Factory
创建子类:CookieC ; CookieR ; Cookies,继承 Cookie
工厂模式:利用多态 完成批量更改生产结果的任务
当需要更改结果时 只需要更改模型就可以
Factory.h
#import <Foundation/Foundation.h>
#import "Cookie.h"
@interface Factory : NSObject
@property (nonatomic,copy)NSString *modelName;
- (Cookie *)createCookie;
@end
Factory.m
@implementation Factory
- (Cookie *)createCookie
{
//将保存在工厂属性中的字符串转化为类名
Class class = NSClassFromString(_modelName);
//多态:父类声明子类对象 - > 通过上面的类名创建对应的对象
Cookie *cookie = [[class alloc]init];
//将结果传出
return cookie;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Factory.h"
#import "Cookie.h"
int main(int argc , const char *argv[])
{
@autoreleasepool
{
//我们创建的类或者框架中提供的类的名字 都有一个统一的类型Class
//通过字符串 构造 类名 --> 将字符串转化为类名
Class class = NSClassFromString(@"Factory");
/*
我们有工厂类Factory 生产 饼干类 Cookie
*/
//创建工厂
Factory *factory = [[Factory alloc]init];
//设置生产模板
factory.modelName = @"Cookies";
//批量生产
Cookie *c1 = [factory createCookie];
Cookie *c2 = [factory createCookie];
Cookie *c3 = [factory createCookie];
Cookie *c4 = [factory createCookie];
Cookie *c5 = [factory createCookie];
NSLog(@"%@",c1);
NSLog(@"%@",c2);
NSLog(@"%@",c3);
NSLog(@"%@",c4);
NSLog(@"%@",c1);
}
return 0;
}