通过上面的分析,我们大致可以总结出工厂这种设计模式的应用场景:
(1)当一个类并不知道要创建的具体对象是什么,交由子类处理
(2)当一些类有相似的行为和结构,只是具体实现不同时,可以抽象出工厂
(3)使用者并不在乎具体类型,只在乎接口约定的行为,并且这种行为有个体差异
实例我借鉴了珲少的工程文档 首先,我们创建一个抽象的工程类,在其中创建一些私有的子类: 实现文件如下: 这样,我们的一个生产工厂就完成了,在外面,我们只需要知道一个类,我们的抽象父类,就可以实现个子类的行为,示例如下: 可以看到,对于开发者,我们并不知晓CarFactory类的存在,我们只需要通过TramsPortationFactory类,就能够操作各种交通工具,达到我们的需求。#import <Foundation/Foundation.h>
//交通工具的枚举
typedef
enum
{
car,
boat,
airport,
bycicle,
bus,
taxi
}ToolsName;
//代理
@protocol TransPortationDelegate <NSObject>
-(
void
)toHome:(Class)
class
;
@end
//抽象工厂类
@interface TramsPortationFactory : NSObject
+(TramsPortationFactory*)buyTool:(ToolsName)tool;
//共有的方法接口
-(
int
)shouldPayMoney;
-(
void
)run;
@property(nonatomic,strong)id<TransPortationDelegate>delegate;
@end
//具体实现的子类
@interface CarFactory : TramsPortationFactory
@end
@interface BoatFactory : TramsPortationFactory
@end
@interface AirportFactory : TramsPortationFactory
@end
@interface BycicleFactory : TramsPortationFactory
@end
@interface TaxiFactory : TramsPortationFactory
@end
@interface BusFactory : TramsPortationFactory
@end
#import "TramsPortationFactory.h"
@implementation TramsPortationFactory
//实现的创建方法
+(TramsPortationFactory*)buyTool:(ToolsName)tool{
switch
(tool) {
case
car:
return
[[CarFactory alloc]init];
break
;
case
airport:
return
[[AirportFactory alloc]init];
break
;
case
bycicle:
return
[[BycicleFactory alloc]init];
break
;
case
boat:
return
[[BoatFactory alloc]init];
break
;
case
taxi:
return
[[TaxiFactory alloc]init];
break
;
case
bus:
return
[[BusFactory alloc]init];
break
;
default
:
break
;
}
}
-(
int
)shouldPayMoney{
return
0;
}
-(
void
)run{
[self.delegate toHome:[self
class
]];
}
@end
//各自类实现具体的行为
@implementation CarFactory
-(
int
)shouldPayMoney{
return
50;
}
-(
void
)run{
[super run];
NSLog(@
"car to home"
);
}
@end
@implementation AirportFactory
-(
int
)shouldPayMoney{
return
1000;
}
-(
void
)run{
[super run];
NSLog(@
"fly to home"
);
}
@end
@implementation BoatFactory
-(
int
)shouldPayMoney{
return
300;
}
-(
void
)run{
[super run];
NSLog(@
"boat to home"
);
}
@end
@implementation BusFactory
-(
int
)shouldPayMoney{
return
10;
}
-(
void
)run{
[super run];
NSLog(@
"bus to home"
);
}
@end
@implementation BycicleFactory
-(
int
)shouldPayMoney{
return
0;
}
-(
void
)run{
[super run];
NSLog(@
"run to home"
);
}
@end
@implementation TaxiFactory
-(
int
)shouldPayMoney{
return
100;
}
-(
void
)run{
[super run];
NSLog(@
"go to home"
);
}
@end
- (
void
)viewDidLoad {
[super viewDidLoad];
TramsPortationFactory * tool = [TramsPortationFactory buyTool:car];
tool.delegate=self;
[tool run];
NSLog(@
"花了:%d钱"
,[tool shouldPayMoney]);
TramsPortationFactory * tool2 = [TramsPortationFactory buyTool:airport];
tool2.delegate=self;
[tool2 run];
NSLog(@
"花了:%d钱"
,[tool2 shouldPayMoney]);
}
-(
void
)toHome:(Class)
class
{
NSLog(@
"%@"
,NSStringFromClass(
class
));
}
原文:http://www.cnblogs.com/G-Flager/p/5304291.html