Design Patterns - Factory Method
阿新 • • 發佈:2020-12-11
Factory Method(工廠方法) — 物件建立型模式
定義一個用於建立物件的介面,讓子類決定例項化哪一個類。Factory Method 使一個類的例項化延遲到其子類(抽象工廠模式中就使用到了工廠方法)
適用場景
- 當一個類不知道它所必須建立的物件的類的時候
- 當一個類希望由它的子類來指定它所建立的物件的時候
優點
- 工廠方法不再將與特定應用有關的類繫結到你的程式碼中。程式碼僅處理 Product 介面,因此它可以與使用者定義的任何 COncreteProduct 類一起使用。
缺點
- 建立一個特定的 ConcreteProduct 物件,就不得不建立 Creator 的子類。
其他一些需要考慮的問題
- Factory Method 模式主要有兩種不同的情況:1. Creator 類是一個抽象類並且不提供它所宣告的工廠方法的實現;2. Creator 是一個具體的類而且為工廠方法提供一個預設的實現。第一種情況需要子類來定義實現,因為沒有合理的預設實現。它避免了不得不實現不可預見類的問題。在第二種情況下,你也可以在必要時過載父類。
- 引數化工廠方法,有些情況下可以使一個Creator建立多個產品,即採用一個標識作為要被建立的物件種類的引數。
class Creator {
public:
virtual Product *Create(ProductId) ;
};
Product* Creator::Create (ProductId id) {
if (id == MINE) return new MyProduct;
if (id == YOURS) return new YourProduct;
// repeat for remaining productes...
return 0;
}
UML 圖
示例
class PhoneProduct(object):
def start(self):
raise NotImplementedError
def shutdown (self):
raise NotImplementedError
def callup(self):
raise NotImplementedError
def sendSMS(self):
raise NotImplementedError
class XiaomiPhone(PhoneProduct):
def start(self):
print("開啟小米手機")
def shutdown(self):
print("關閉小米手機")
def callup(self):
print("用小米手機打電話")
def sendSMS(self):
print("用小米手機發簡訊")
class HuaweiPhone(PhoneProduct):
def start(self):
print("開啟華為手機")
def shutdown(self):
print("關閉華為手機")
def callup(self):
print("用華為手機打電話")
def sendSMS(self):
print("用華為手機發簡訊")
class Creator(object):
def createPhone(self):
raise NotImplementedError
def work(self):
phone = self.createPhone()
phone.start()
phone.callup()
phone.sendSMS()
phone.shutdown()
class XiaomiPhoneCreator(Creator):
def createPhone(self):
return XiaomiPhone()
class HuaweiPhoneCreator(Creator):
def createPhone(self):
return HuaweiPhone()
client
creator = XiaomiPhoneCreator()
creator.work()
print("****************")
creator = HuaweiPhoneCreator()
creator.work()
"""output
開啟小米手機
用小米手機打電話
用小米手機發簡訊
關閉小米手機
****************
開啟華為手機
用華為手機打電話
用華為手機發簡訊
關閉華為手機
"""