抽象工厂模式
简单工厂是一个实体类,包含了根据不同参数直接创建对象的方法。而抽象工厂(Abstract Factory pattern)则是在简单工厂的基础上将(多个)工厂类进一步进行抽象(如UML图示):
在工程中,我们创建了两个实体类:动物类(Animal)和植物类(Plant);这两个类分别遵循协议AnimalProtocol和PlantProtocol;分别有子类Dog、Fish、Bird(继承自Animal类)和Rose、Sakura(继承自Plant类);这两个实体类分别通过工厂类AnimalFactory和PlantFactory进行实例化(均继承自BioligyFactory工厂类);在此基础上,将工厂类进一步抽象,通过抽象工厂类AbstractFactory对工厂类进行实例化。
代码实现:
1.Animal、AnimalFactory、BiologyFactory
Animal、AnimalFactory代码在《简单工厂模式》中已经创建,只需要将AnimaFactory继承于BiologyFactory并将类方法改为实例方法即可。
1 // BiologyFactory.h 2 #import <Foundation/Foundation.h> 3 #import "Plant.h" 4 #import "Animal.h" 5 6 typedef NS_ENUM(NSInteger, EFactory){ 7 kAnimalFactory, 8 kPlantFactory, 9 }; 10 11 typedef NS_ENUM(NSInteger, EPlantType){ 12 kRose, 13 kSakura, 14 }; 15 16 typedef enum { 17 kDog, 18 kBird, 19 kFish, 20 }EAnimalType; 21 22 @interface BiologyFactory : NSObject 23 24 - (Plant*)createPlantWithType:(EPlantType)type; 25 26 - (Animal*)createAnimalWithType:(EAnimalType)type; 27 28 @end
2.Plant、PlantFactory
1 // Plant.h 2 #import <Foundation/Foundation.h> 3 4 @protocol PlantProtocol <NSObject> 5 @optional 6 - (void)flower; 7 - (void)color; 8 @end 9 10 @interface Plant : NSObject<PlantProtocol> 11 12 @end 13 14 // Rose.h 15 #import "Plant.h" 16 17 @interface Rose : Plant 18 19 - (void)thorn; 20 21 @end 22 23 // Sakura.h 24 #import "Plant.h" 25 26 @interface Sakura : Plant 27 28 - (void)enjoyFlower; 29 30 @end
1 // PlantFactory.h 2 #import "BiologyFactory.h" 3 #import "Rose.h" 4 #import "Sakura.h" 5 6 @interface PlantFactory : BiologyFactory 7 8 - (Plant*)createPlantWithType:(EPlantType)type; 9 10 @end 11 12 // PlantFactory.m 13 #import "PlantFactory.h" 14 15 @implementation PlantFactory 16 17 - (Plant *)createPlantWithType:(EPlantType)type{ 18 Plant *plant = nil; 19 if(type == kRose){ 20 plant = [Rose new]; 21 }else if(type == kSakura){ 22 plant = [Sakura new]; 23 } 24 return plant; 25 } 26 27 @end
3.AbstractFactory创建
1 // AbstractFactory.h 2 #import <Foundation/Foundation.h> 3 #import "BiologyFactory.h" 4 #import "AnimalFactory.h" 5 #import "PlantFactory.h" 6 7 @interface AbstractFactory : NSObject 8 9 + (BiologyFactory*)createFactoryWithType:(EFactory)type; 10 11 @end 12 13 // AbstractFactory.m 14 #import "AbstractFactory.h" 15 16 @implementation AbstractFactory 17 18 + (BiologyFactory*)createFactoryWithType:(EFactory)type{ 19 BiologyFactory *factory = nil; 20 if(type == kAnimalFactory){ 21 factory = [AnimalFactory new]; 22 }else if(type == kPlantFactory){ 23 factory = [PlantFactory new]; 24 } 25 return factory; 26 } 27 28 @end