工廠模式就是我們在創建對象時不會對客戶端暴露創建邏輯,并且是通過使用一個共同的接口來指向新創建的對象。
工廠模式又分為簡單工廠模式,工廠方法模式,抽象工廠模式。
下面的三張圖,完美的解釋了什么是工廠模式。
簡單工廠模式
1419489-20190628144601084-563759643.png
工廠方法模式
1419489-20190628154133368-906051111.png
抽象工廠模式
1419489-20190628170705865-1781414242.png
工廠模式優點
一個調用者想創建一個對象,只要知道其名稱就可以了。
擴展性高,如果想增加一個產品,只要擴展一個工廠類就可以。
屏蔽產品的具體實現,調用者只關心產品的接口。
工廠模式缺點
每次增加一個產品時,都需要增加一個具體類和對象實現工廠,使得系統中類的個數成倍增加,在一定程度上增加了系統的復雜度,同時也增加了系統具體類的依賴。這并不是什么好事。
其實如果懂了抽象工廠模式,上面的兩種模式也就都懂了。所以看下面這個例子。
現在我們要創建兩個工廠,一個是蘋果廠,一個是谷歌廠,同時蘋果廠可以生產蘋果手機和蘋果手表,谷歌廠可以生產安卓手機和安卓手表,同時每部手機不光可以打電話,發短信,還都有自己獨特的功能,蘋果手機可以指紋識別,安卓可以主題定制。
需要先創建工廠基類。
@implementation BaseFactory
- (BasePhone *)createPhone {
return nil;
}
- (BaseWatch *)createWatch {
return nil;
}
@end
然后根據基類分別創建蘋果廠和谷歌廠。
@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
然后創建手機基類。
@interface BasePhone : NSObject <PhoneProtocol>
@end
@implementation BasePhone
- (void)phoneCall {
}
- (void)sendMessage {
}
@end
根據手機基類創建不同的手機。
@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
創建不同工廠的工廠管理類。
typedef NS_ENUM(NSUInteger, KFactoryType) {
KApple,
KGoogle
};
@interface FactoryManager : NSObject
/**
獲取工廠
@param factoryType 工廠類型
@return 創建出的工廠
*/
+ (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
那么下面就是來使用了,屏蔽內部實現,通過不同工廠類組裝成的抽象工廠模式
// 獲取工廠
BaseFactory *googleFactory = [FactoryManager factoryWithBrand:KGoogle];
// 創建商品
Android *androidPhone = (Android *)[googleFactory createPhone];
BaseWatch *androidWatch = [googleFactory createWatch];
[androidPhone phoneCall];
//定制主題
[androidPhone customTheme];
// 獲取工廠
BaseFactory *appleFactory = [FactoryManager factoryWithBrand:KApple];
// 創建商品
IPhone *applePhone = (IPhone *)[appleFactory createPhone];
BaseWatch *appleWatch = [appleFactory createWatch];
[applePhone phoneCall];
//指紋識別
[applePhone fingerprintIndetification];