设计模式,很早接触到软件编程的时候,就经常听到人说,设计模式的灵活应用是高级软件工程师必备,以及各种高大上的修饰.最初接触设计模式,应该是借同学的<大话设计模式>,在这里推荐一下,蛮不错的.然后,最火的应该是GOF的23种设计模式,不过我没怎么看,^_^.随着自身学习和工作的不断加深,觉得很有必要认真仔细的去研究一下了,因为自身主要开发iOS,所以,参考我标题的这本书为主.
@ 基本描述
GOF是这样描述工厂模式的:
“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”
在基类中定义创建对象的一个接口,让子类决定实例化哪个类。工厂方法让一个类的实例化延迟到子类中进行。
工厂方法要解决的问题是对象的创建时机,它提供了一种扩展的策略,很好地符合了开放封闭原则。工厂方法也叫做虚构造器(Virtual Constructor).
@什么时候使用工厂方法?
@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即可
- }