定義
抽象工廠模式提供了一個介面,建立相關或相依物件之家族,而不需要明確指定具象類別。
Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their concrete classes.
解說
- Abstract Factory is one of the Creational Patterns.
- 抽象工廠定義了一個介面,所有的具象工廠都必須實踐此介面,這個介面包含一整組的方法來生產產品。
- 抽象工廠的方法經常以工廠方法的方式實踐:這個介面的每個方法負責建立一個具象產品,同時利用實踐抽象工廠的次類別提供具體做法。
- 每個具象工廠實踐不同的產品家族,產生一整組的產品。客戶只要使用其中一個工廠來製造產品,不需實體化任何產品物件。
- 客戶的程式碼中只需涉及抽象工廠,執行期將自動使用實際的工廠。
- The client doesn't have knowledge of the object's type, so there's no need to include concrete type. The client only deal with the abstract type.
- The objects of the concrete type, created by the factory, are accessed by the client only through the abstract interface.
缺:如果加入新產品,就必須改變介面。
Factory Method VS Abstract Factory
- 工廠方法透過類別的繼承來建立物件,次類別實踐工廠方法以建立物件;
- 抽象工廠提供一個抽象型態,藉由物件的合成來建立一個產品家族,這個型態的次類別定義了產品被產生的方法(工廠方法)。
Summary
抽象工廠允許client使用抽象的介面,建立一組相關的產品,而不需要知道實際產出的concrete type為何。Therefore,client is decoupled from concrete object。
對於有變動性的物件,應該避免依賴具象類別,而要盡量抽象。工廠模式幫助我們針對抽象寫程式,而不要針對具象類別寫程式。