@什么时候使用工厂方法?
@iOS中工厂方法的简单实现
举个例子,有一家生产衣服的工厂,它生产2种型号的衣服,一个为DOTA类,一个为LOL类,经销商需要进什么类型的货一定要显示的告诉工厂,生产指定的类型,这样很麻烦,后来它有钱了,开了两家工厂,一家单独生产DOTA类,一家单独生产LOL类,这样,经销商进货直接去找对应的工厂就行.
- #import <Foundation/Foundation.h>
- @interface HMTClothes : NSObject
- // 展示衣服类型
- - (void)showClothesType;
- @end
- #import "HMTClothes.h"
- @implementation HMTClothes
- - (void)showClothesType{
- }
- @end
- #import "HMTClothes.h"
- @interface HMTClothes_Dota : HMTClothes
- - (void)showClothesType;
- @end
- #import "HMTClothes_Dota.h"
- @implementation HMTClothes_Dota
- - (void)showClothesType{
- NSLog(@"这件衣服的类型是Dota");
- }
- @end
- #import "HMTClothes.h"
- @interface HMTClothes_LOL : HMTClothes
- - (void)showClothesType;
- @end
- #import "HMTClothes_LOL.h"
- @implementation HMTClothes_LOL
- - (void)showClothesType{
- NSLog(@"这件衣服的类型是LOL");
- }
- @end
- #import <Foundation/Foundation.h>
- @class HMTClothes;
- @interface HMTClothesFactory : NSObject
- - (HMTClothes *)makeClothes;
- @end
- #import "HMTClothesFactory.h"
- @implementation HMTClothesFactory
- - (HMTClothes *)makeClothes{
- return nil;
- }
- @end
- #import "HMTClothesFactory.h"
- @interface HMTClothesDotaFactory : HMTClothesFactory
- - (HMTClothes *)makeClothes;
- @end
- #import "HMTClothesDotaFactory.h"
- #import "HMTClothes_Dota.h"
- @implementation HMTClothesDotaFactory
- - (HMTClothes *)makeClothes{
- return [[HMTClothes_Dota alloc] init];
- }
- @end
- #import "HMTClothesFactory.h"
- @interface HMTClothesLOLFactory : HMTClothesFactory
- - (HMTClothes *)makeClothes;
- @end
- #import "HMTClothesLOLFactory.h"
- #import "HMTClothes_LOL.h"
- @implementation HMTClothesLOLFactory
- - (HMTClothes *)makeClothes{
- return [[HMTClothes_LOL alloc] init];
- }
- @end
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- /**
- * 实例变量的类型,是由进行了alloc的Class决定的,一般也就是等号的右边
- * 就好比,NSMutableArray * mutableArray = 一个类型为NSArray的数组;它的实质还是一个NSArray类型,并
- * 不能调用NSMutableArray的方法
- */
- HMTClothesFactory *clothesFactory = [[HMTClothesDotaFactory alloc] init];
- HMTClothes *clothes = [clothesFactory makeClothes];
- [clothes showClothesType]; // -->输出的是"这件衣服的类型是Dota"
- // 如果你想制造LOL衣服,直接把HMTClothesDotaFactory->HMTClothesLOLFactory即可
- }