工厂模式
概念:
专门定义一个类来负责创建其他类的实例,被创建的实例通常具有相同的父类
简单的工厂模式
我们新建如下类:(Cat类与Dog类继承于Animal类)
我们先简单的为我们动物类声明一个吃的方法:
#import <Foundation/Foundation.h>
@interface Animal : NSObject
-(void)eat;
@end
然后我们分别在Cat类和Dog类中重写eat方法:
#import "Cat.h"
@implementation Cat
-(void)eat{
NSLog(@"猫吃鱼");
}
@end
#import "Dog.h"
@implementation Dog
-(void)eat{
NSLog(@"狗吃骨");
}
@end
在AnimalFactory类文件中,我们导入狗类和猫类,声明并实现两个创建狗类和猫类的对象的方法:
#import <Foundation/Foundation.h>
#import "Dog.h"
#import "Cat.h"
@interface AnimalFactory : NSObject
+(Dog *)createDog;
+(Cat *)createCat;
@end
#import "AnimalFactory.h"
@implementation AnimalFactory
+(Dog *)createDog{
Dog *dog=[[Dog alloc]init];
return dog;
}
+(Cat *)createCat{
Cat *cat=[[Cat alloc]init];
return cat;
}
@end
最后我们在主函数中测试一下:
Dog *dog=[AnimalFactory createDog];
Cat *cat=[AnimalFactory createCat];
[dog eat];
[cat eat];
更好的的工厂模式
我们如果要创建大量的对象,而且分别位于一个项目的不同地方,那如果我们要去更改这个对象所属于的类时,会显得非常的麻烦,这时候我们就要用到更好的工厂模式:
首先,我们在刚刚建立的AnimalFactory中,声明一个更好的关于创建动物的方法;
-(AnimalFactory *)createAnimal;
然后,我们在去新建两个关于猫和狗类创建对象相关的工厂类,在这两个类里面重写)createAnimal方法:
#import "CatFactory.h"
@implementation CatFactory
-(AnimalFactory *)createAnimal{
return [Cat new];
}
@end
#import "DogFactory.h"
@implementation DogFactory
-(AnimalFactory *)createAnimal{
return [Dog new];
}
@end
最后在主函数导入好工厂的头文件测试一下:
AnimalFactory *factory=[DogFactory new];
Animal *animal1=[factory createAnimal];
[animal1 eat];
Animal *animal2=[factory createAnimal];
[animal2 eat];