iOS設計模式 《工廠模式》

2021-07-14 23:28:50 字數 2636 閱讀 4649

1 何為工廠模式?

工廠方法也稱為虛構造器。它適用於乙個類無法預期需要生成那個類的物件,想讓子類來指定所生成的物件。

抽象的product(產品)定義了工廠方法建立的物件的接中。concreteproduct實現了product的介面。create定義了返回product物件的工廠方法。它也可以為工廠方法定義乙個預設實現,返回預設concreateproduct物件。creator的其他操作可以呼叫此工廠方法建立product物件。concreatecreator是creator的子類。他過載了工廠方法,已返回concreteproduct的例項  選自《ios設計模式 51頁》
個人理解就是:父類定義乙個建立物件的介面,讓子類去決定例項化那個乙個類,把物件的例項化延遲到了子類,感覺也就是和多型差不多的。

2 何時使用工廠方法?

編譯時無法準確預期要建立的物件的類。

類想讓其子類決定的執行時建立什麼

類有若干輔助類為其子類,而你想將返回那個子類這一資訊區域性化

現在有點雨裡霧裡的,只能用例子來撥開迷霧了。這裡借用別人的乙個例子。不過最好自己寫一寫,這樣更明白。

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

衣服的父類

hmtclothes.h

@inte***ce

hmtclothes : nsobject

- (void)showclothestype;

@end

hmtclothes.m

@implementation

hmtclothes

- (void)showclothestype

@end

dota衣服類繼承與衣服類

hmtclothes_dota.h

@inte***ce

hmtclothes_dota : hmtclothes

- (void)showclothestype;

@end

hmtclothes_dota.m

@implementation

hmtclothes_dota

- (void)showclothestype

@end

lol類必須繼承與同乙個父類

hmtclothes_lol.h

@inte***ce

hmtclothes_lol : hmtclothes

- (void)showclothestype;

@end

@implementation

hmtclothes_lol

- (void)showclothestype

@end

工廠類,通過這個類決定是dota衣服的工廠類還是lol衣服的類

hmtclothesfactory

.h@class hmtclothes;

@inte***ce hmtclothesfactory : nsobject

- (hmtclothes *)makeclothes;

@end

@implementation

hmtclothesfactory

- (hmtclothes *)makeclothes

@end

hmtclothesdotafactory dota類,通過這類返回相對應的衣服類

hmtclothesdotafactory

.h@inte***ce hmtclothesdotafactory : hmtclothesfactory

- (hmtclothes *)makeclothes;

@end

@implementation hmtclothesdotafactory

- (hmtclothes *)makeclothes

@end

hmtclotheslolfactory

.h@inte***ce hmtclotheslolfactory : hmtclothesfactory

- (hmtclothes *)makeclothes;

@end

@implementation hmtclotheslolfactory

- (hmtclothes *)makeclothes

@end

vc中:

- (void)viewdidload

iOS 設計模式之工廠模式

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

iOS設計模式之簡單工廠模式

最近在看關於設計模式的書籍,開始覺得在設計程式架構之時,能夠靈活運用這些設計模式,將變得非常具有美感。乙個好的設計模式使得程式更加的靈活,容易修改,易於使用。從最簡單的簡單工廠模式開始學起,舉乙個實現計算器的例子,來完成簡單工廠模式。乙個簡單計算器,用四則運算來考慮的話,加減乘除,那麼初學者會覺得很...

iOS設計模式之簡單工廠模式

乙個簡單計算器,用四則運算來考慮的話,加減乘除,那麼初學者會覺得很簡單,用if條件來進行判斷,判斷好了之後就可以完成要求,而稍微有經驗點的 可能會選擇switch case的判斷方式,例如下面的 operation運算方法的邏輯 void operationwithnumbera double nu...