iOS 设计模式之工厂模式

什么是工厂方法?ide

GOF是这样描述工厂模式的:atom

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”spa

在基类中定义建立对象的一个接口,让子类决定实例化哪一个类。工厂方法让一个类的实例化延迟到子类中进行。.net

工厂方法要解决的问题是对象的建立时机,它提供了一种扩展的策略,很好地符合了开放封闭原则。工厂方法也叫作虚构造器(Virtual Constructor)。orm

 

何时使用工厂方法?对象

当是以下状况是,可使用工厂方法:一个类不知道它所必须建立的对象的类时,一个类但愿有它的子类决定所建立的对象时。接口


工厂模式个人理解是:他就是为了建立对象的ci

建立对象的时候,咱们通常是alloc一个对象,若是须要建立100个这样的对象,若是是在一个for循环中还好说,直接一句alloc就好了,可是事实并不那么如意,咱们可能会在不一样的地方去建立这个对象,那么咱们可能须要写100句alloc 了,可是若是咱们在建立对象的时候,须要在这些对象建立完以后,为它的一个属性添加一个固定的值,比方说都是某某学校的学生,那么可能有须要多些100行重复的代码了,那么,若是写一个-(void)createObj方法,把建立对象和学校属性写在这个方法里边,那么就是会省事不少,也就是说咱们能够alloc 建立对象封装到一个方法里边,直接调用这个方法就能够了,这就是简单工厂方法get

代码结构以下it

Animal 类

@interface Animal :NSObject

@proterty(nonatomic,strong) NSString *name;

-(void)laugh;

@end

Dog类


@interface Dog:Animal

@end


Cat类

@interface Cat:Animal

@end


建立对象的工厂类

.h

@interface AnimalFactory:NSObject

+(Dog *)createDog;

+(Cat *)createCat;

@end

.m

@implementation AnimalFactory

+(Dog *)createDog{

    Dog *dog=[[Dog alloc]init];

    dog.name=@“baby”;

    return dog;

}


+(Cat *) createCat{

    Cat *cat=[[Cat alloc]init];

    return cat;

}

Main.m文件

Dog *dog=[AnimalFactory createDog];

Cat *cat=[AnimalFactory createCat];

这是简单工厂模式

如今建立100个Dog对象,若是这100个对象写在程序中的不一样地方,按上边的方法是须要把Dog *dog=[AnimalFactory createDog];这一句话写在程序中不少不一样的地方,那么如今有一个需求,就是若是须要把这些建立的100个Dog对象所有变成Cat对象,那么按照刚才的那个作法,就须要在这100句代码中把createDog方法变成createCat方法了,这样作仍是很复杂

那么这个时候用工厂方法模式就能解决这个难题了

工厂方法模式是为每个要建立的对象所在的类都相应地建立一个工厂

代码以下

@interface AnimalFactory:NSObject

-(Animal*)createAnimal;

@end;

Dog工厂类

@interface DogFactory:AnimalFactory;

@implementation DogFactory

-(Animal *)createAnimal{

retrurn [[Dog alloc]init];

}

@end

Cat工厂类

@interface CatFactory:AnimalFactory;

@implementation Cat Factory

-(Animal *)createAnimal

retrurn [[Cat alloc]init];

}

@end

Main.m

AnimalFactory *dogFactory=[[DogFactory alloc]init];


Animal *animal1=[dogFactory createAnimal];

[animal1 laugh];

Animal *animal2=[dogFactory createAnimal];

[animal2 laugh];

…….

Animal *animal100=[dogFactory createAnimal];

[animal100 laugh];

这样话若是要把100个Dog改成Cat的话,只须要吧DogFactory改成CatFactory就能够了


可是工厂方法也有它的限制:

1.要建立的类必须拥有同一个父类

2.要建立的类在100个不一样的地方所调用的方法必须同样

相关文章
相关标签/搜索