工廠模式就是我們在創(chuàng)建對象時不會對客戶端暴露創(chuàng)建邏輯,并且是通過使用一個共同的接口來指向新創(chuàng)建的對象。
工廠模式又分為簡單工廠模式,工廠方法模式,抽象工廠模式。
下面的三張圖,完美的解釋了什么是工廠模式。
簡單工廠模式

1419489-20190628144601084-563759643.png
工廠方法模式

1419489-20190628154133368-906051111.png
抽象工廠模式

1419489-20190628170705865-1781414242.png
工廠模式優(yōu)點(diǎn)
一個調(diào)用者想創(chuàng)建一個對象,只要知道其名稱就可以了。
擴(kuò)展性高,如果想增加一個產(chǎn)品,只要擴(kuò)展一個工廠類就可以。
屏蔽產(chǎn)品的具體實(shí)現(xiàn),調(diào)用者只關(guān)心產(chǎn)品的接口。
工廠模式缺點(diǎn)
每次增加一個產(chǎn)品時,都需要增加一個具體類和對象實(shí)現(xiàn)工廠,使得系統(tǒng)中類的個數(shù)成倍增加,在一定程度上增加了系統(tǒng)的復(fù)雜度,同時也增加了系統(tǒng)具體類的依賴。這并不是什么好事。
其實(shí)如果懂了抽象工廠模式,上面的兩種模式也就都懂了。所以看下面這個例子。
現(xiàn)在我們要創(chuàng)建兩個工廠,一個是蘋果廠,一個是谷歌廠,同時蘋果廠可以生產(chǎn)蘋果手機(jī)和蘋果手表,谷歌廠可以生產(chǎn)安卓手機(jī)和安卓手表,同時每部手機(jī)不光可以打電話,發(fā)短信,還都有自己獨(dú)特的功能,蘋果手機(jī)可以指紋識別,安卓可以主題定制。
需要先創(chuàng)建工廠基類。
@implementation BaseFactory
- (BasePhone *)createPhone {
return nil;
}
- (BaseWatch *)createWatch {
return nil;
}
@end
然后根據(jù)基類分別創(chuàng)建蘋果廠和谷歌廠。
@implementation AppleFactory
- (BasePhone *)createPhone {
return [[IPhone alloc] init];
}
- (BaseWatch *)createWatch {
return [[IWatch alloc] init];
}
@end
@implementation GoogleFactory
- (BasePhone *)createPhone {
return [[Android alloc] init];
}
- (BaseWatch *)createWatch {
return [[AndroidWatch alloc] init];
}
@end
然后創(chuàng)建手機(jī)基類。
@interface BasePhone : NSObject <PhoneProtocol>
@end
@implementation BasePhone
- (void)phoneCall {
}
- (void)sendMessage {
}
@end
根據(jù)手機(jī)基類創(chuàng)建不同的手機(jī)。
@implementation IPhone
- (void)phoneCall {
NSLog(@"iPhone phoneCall");
}
- (void)sendMessage {
NSLog(@"iPhone sendMessage");
}
- (void)fingerprintIndetification {
NSLog(@"iPhone fingerprintIndetification");
}
@end
@implementation Android
- (void)phoneCall {
NSLog(@"Android phoneCall");
}
- (void)sendMessage {
NSLog(@"Android sendMessage");
}
- (void)customTheme {
NSLog(@"Android customTheme");
}
@end
創(chuàng)建不同工廠的工廠管理類。
typedef NS_ENUM(NSUInteger, KFactoryType) {
KApple,
KGoogle
};
@interface FactoryManager : NSObject
/**
獲取工廠
@param factoryType 工廠類型
@return 創(chuàng)建出的工廠
*/
+ (BaseFactory *)factoryWithBrand:(KFactoryType)factoryType;
@end
+ (BaseFactory *)factoryWithBrand:(KFactoryType)factoryType {
BaseFactory *factory = nil;
if (factoryType == KApple) {
factory = [[AppleFactory alloc] init];
} else if (factoryType == KGoogle) {
factory = [[GoogleFactory alloc] init];
}
return factory;
}
@end
那么下面就是來使用了,屏蔽內(nèi)部實(shí)現(xiàn),通過不同工廠類組裝成的抽象工廠模式
// 獲取工廠
BaseFactory *googleFactory = [FactoryManager factoryWithBrand:KGoogle];
// 創(chuàng)建商品
Android *androidPhone = (Android *)[googleFactory createPhone];
BaseWatch *androidWatch = [googleFactory createWatch];
[androidPhone phoneCall];
//定制主題
[androidPhone customTheme];
// 獲取工廠
BaseFactory *appleFactory = [FactoryManager factoryWithBrand:KApple];
// 創(chuàng)建商品
IPhone *applePhone = (IPhone *)[appleFactory createPhone];
BaseWatch *appleWatch = [appleFactory createWatch];
[applePhone phoneCall];
//指紋識別
[applePhone fingerprintIndetification];