iOS 設計模式之原廠模式,ios設計模式工廠
原廠模式我的理解是:他就是為了建立對象的
建立對象的時候,我們一般是alloc一個對象,如果需要建立100個這樣的對象,如果是在一個for迴圈中還好說,直接一句alloc就行了,但是事實並不那麼如意,我們可能會在不同的地方去建立這個對象,那麼我們可能需要寫100句alloc 了,但是如果我們在建立對象的時候,需要在這些對象建立完之後,為它的一個屬性添加一個固定的值,比方說都是某某學校的學生,那麼可能有需要多些100行重複的代碼了,那麼,如果寫一個-(void)createObj方法,把建立對象和學校屬性寫在這個方法裡邊,那麼就是會省事很多,也就是說我們可以alloc 建立對象封裝到一個方法裡邊,直接調用這個方法就可以了,這就是簡單Factory 方法
代碼結構如下
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方法了,這樣做還是很複雜
那麼這個時候用Factory 方法模式就能解決這個難題了
Factory 方法模式是為每一個要建立的對象所在的類都相應地建立一個工廠
代碼如下
@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就可以了
但是Factory 方法也有它的限制:
1.要建立的類必須擁有同一個父類
2.要建立的類在100個不同的地方所調用的方法必須一樣
以上這些只是個人感悟,會有一些不足的地方,請大家幫忙改正,嘿嘿