iOS 工廠模式

2021-07-22 05:59:14 字數 3155 閱讀 1443

一、gof是這樣描述工廠模式的:

「define an inte***ce for creating an object, but let subclasses decide which class to instantiate. factory method lets a class defer instantiation to subclasses.」

在基類中定義建立物件的乙個介面,讓子類決定例項化哪個類。工廠方法讓乙個類的例項化延遲到子類中進行。

「專門定義乙個類來負責建立其他類的例項,被建立的例項常常具有共同的父類。」

實際上就是由乙個工廠類,根據傳入的引數,動態的決定建立出哪乙個產品類的例項。

工廠方法要解決的問題是物件的建立時機,它提供了一種擴充套件的策略,很好地符合了開放封閉原則。工廠方法也叫做虛構造器(virtual constructor).

二、什麼時候使用工廠方法?

三、ios中工廠方法的簡單實現

舉個例子,有一家生產衣服的工廠,它生產2種型號的衣服,乙個為dota類,乙個為lol類,經銷商需要進什麼型別的貨一定要顯示的告訴工廠,生產指定的型別,這樣很麻煩,後來它有錢了,開了兩家工廠,一家單獨生產dota類,一家單獨生產lol類,這樣,經銷商進貨直接去找對應的工廠就行.  

#

import

@inte***ce

hmtclothes

: nsobject

// 展示衣服型別

- (void

)showclothestype;

@end

#import

"hmtclothes.h"

@implementation

hmtclothes

- (void

)showclothestype

@end

#import

"hmtclothes.h"

@inte***ce

hmtclothes_dota

: hmtclothes

- (void

)showclothestype;

@end

#import

"hmtclothes_dota.h"

@implementation

hmtclothes_dota

- (void

)showclothestype

@end

#import

"hmtclothes.h"

@inte***ce

hmtclothes_lol

: hmtclothes

- (void

)showclothestype;

@end

#import

"hmtclothes_lol.h"

@implementation

hmtclothes_lol

- (void

)showclothestype

@end

#

import

@class

hmtclothes;

@inte***ce

hmtclothesfactory

: nsobject

- (hmtclothes *)makeclothes;

@end

#import

"hmtclothesfactory.h"

@implementation

hmtclothesfactory

- (hmtclothes *)makeclothes

@end

#import

"hmtclothesfactory.h"

@inte***ce

hmtclothesdotafactory

: hmtclothesfactory

- (hmtclothes *)makeclothes;

@end

#import

"hmtclothesdotafactory.h"

#import

"hmtclothes_dota.h"

@implementation

hmtclothesdotafactory

- (hmtclothes *)makeclothes

@end

#import

"hmtclothesfactory.h"

@inte***ce

hmtclotheslolfactory

: hmtclothesfactory

- (hmtclothes *)makeclothes;

@end

#import

"hmtclotheslolfactory.h"

#import

"hmtclothes_lol.h"

@implementation

hmtclotheslolfactory

- (hmtclothes *)makeclothes

@end

- (

void

)viewdidload

通過以上的結構圖和**可知,簡單工廠模式主要有三種角色,分別是工廠角色、抽象產品角色和具體產品角色。

工廠類角色:簡單工廠模式的核心,負責根據傳入的引數來例項化具體的產品例項。

抽象產品角色:通常是工廠產生具體類的父類(或者是具體類實現的介面)。

具體產品角色:簡單工廠模式所建立的任何物件都是這個角色的例項。

從上面的介紹可以看出,簡單工廠模式的優點是客戶端可以直接消費產品,而不必關心具體產品的實現,消除了客戶端直接建立產品物件的責任,實現了對責任的分割。

缺點是工廠類集中了所有產品的建立邏輯,一旦不能正常工作,整個系統都會受到影響,而且當產品類別多結構複雜的時候,把所有建立工作放進乙個工廠來,會使後期程式的擴充套件較為困難。

通過優缺點的分析,我們可以在如下場景下使用簡單工廠模式:

工廠類負責建立的物件比較少時;

客戶端只知道傳入工廠類的引數,對於如何建立物件的邏輯不必關心時。

iOS 工廠模式

工廠模式我的理解是 他就是為了建立物件的 建立物件的時候,我們一般是alloc乙個物件,如果需要建立100個這樣的物件,如果是在乙個for迴圈中還好說,直接一句alloc就行了,但是事實並不那麼如意,我們可能會在不同的地方去建立這個物件,那麼我們可能需要寫100句alloc 了,但是如果我們在建立物...

工廠模式 iOS

簡單 介紹一下工廠模式,是為了建立物件,也就是為了建立來自同乙個父類的不同子類物件,動態的去建立物件。下面舉個例子 乙個動物類 import inte ce animal nsobject property nonatomic,strong nsstring name void eat end im...

iOS 工廠模式

工廠模式用於建立某個類的子類例項的 要解決的問題 在其他地方,不確定要建立那個具體的子類的時候使用 import 動物類 作為父類 inte ce animal nsobject void eat end import animal.h implementation animal void eat ...