簡介:抽象工廠模式(Abstract Factory Pattern)是圍繞一個超級工廠創(chuàng)建其他工廠。抽象工廠模式屬于創(chuàng)建型模式。在抽象工廠模式中,接口負責創(chuàng)建一個相關對象的工廠,不需要顯式指定它們的類。每個生成的工廠都能按照工廠模式提供對象。需要擴展時,只需添加對應的子工廠即可。
特性
提供一個創(chuàng)建一系列相關或相互依賴對象的接口,而無須指定它們具體的類。系統(tǒng)的產品有多余一個的產品族,而系統(tǒng)只消費其中某一族的產品。產品族難擴展,產品等級易擴展
優(yōu)點
- 當一個產品族的多個對象被設計成一起工作時,它能保證客戶端始終只使用同一個產品族的對象
缺點
- 產品族擴展非常困難,要增加一個系列的某一產品,既要在抽象的Creater里添加代碼,又要在具體的里面加代碼。
應用場景
- 在一個產品族里面,定義了多個產品。例如:QQ換皮膚,一整套一起換
- 生成不同的操作系統(tǒng)的程序
代碼示例
我們將創(chuàng)建Shape和Color接口和實現(xiàn)這些接口的具體類。下一步是創(chuàng)建抽象工廠類AbstractFactory。接著定義工廠類ShapeFactory和ColorFactory,這兩個工廠類都是擴展了AbstractFactory。然后創(chuàng)建一個工廠創(chuàng)造器類FactoryProducer。如下:
from abc import ABCMeta, abstractmethod
class Shape(object):
_metaclass_ = ABCMeta
@abstractmethod
def draw(self):
pass
class Rectangle(Shape):
def draw(self):
print("Inside Rectangle::draw() method.")
class Square(Shape):
def draw(self):
print("Inside Square::draw() method.")
class Circle(Shape):
def draw(self):
print("Inside Circle::draw() method.")
class Color(object):
_metaclass_ = ABCMeta
@abstractmethod
def fill(self):
pass
class Red(Color):
def fill(self):
print("Inside Red::draw() method.")
class Green(Color):
def fill(self):
print("Inside Green::draw() method.")
class Blue(Color):
def fill(self):
print("Inside Blue::draw() method.")
class AbstractFactory(object):
_metaclass_ = ABCMeta
@abstractmethod
def getColor(self, color):
pass
@abstractmethod
def getShape(self, shape):
pass
class ShapeFactory(AbstractFactory):
def getColor(self, color):
pass
def getShape(self, shape):
if shape == "CIRCLE":
return Circle()
elif shape == "RECTANGLE":
return Rectangle()
elif shape == "SQUARE":
return Square()
class ColorFactory(AbstractFactory):
def getColor(self, color):
if color == "RED":
return Red()
elif color == "GREEN":
return Green()
elif color == "BLUE":
return Blue()
def getShape(self, shape):
pass
class FactoryProducer():
@staticmethod
def getFactory(choice):
if choice == "SHAPE":
return ShapeFactory()
elif choice == "COLOR":
return ColorFactory()
if __name__ == '__main__':
shapeFactory1 = FactoryProducer.getFactory("SHAPE")
shape1 = shapeFactory1.getShape("CIRCLE")
shape1.draw()
shape1 = shapeFactory1.getShape("RECTANGLE")
shape1.draw()
shapeFactory2 = FactoryProducer.getFactory("COLOR")
shape2 = shapeFactory2.getColor("RED")
shape2.fill()
shape2 = shapeFactory2.getColor("GREEN")
shape2.fill()
輸出結果:
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Red::draw() method.
Inside Green::draw() method.
Process finished with exit code 0
總結
提供一個創(chuàng)建一系列相關或相互依賴對象的接口,當一個產品族的多個對象被設計成一起工作時,它能保證客戶端始終只使用同一個產品族的對象。
每天多努力那么一點點,積少成多