普通工厂
工厂模式,可以理解为创建一个工厂(类),这个工厂会根据你的需求(输入)生产出(输出)你想要的产品(对象)。简单说就是工厂类会根据你的输入给你返回恰当的对象。
class Shape:
@staticmethod
def factory(shape):
if shape == 'square':
return Square()
if shape == 'circle':
return Circle()
class Square:
@staticmethod
def draw():
return "I am a Square"
class Circle:
@staticmethod
def draw():
return "I am a Circle"
if __name__ == '__main__':
shape = Shape().factory("square")
print(shape.draw())
shape = Shape().factory("circle")
print(shape.draw())
抽象工厂
抽象工厂:有时候我们希望通过单个接口能够访问所有的工厂,而不用关心具体的工厂,此时就需要定义一个抽象类,让所有的工厂类都继承这个类并实现这个接口。
from abc import ABCMeta, abstractmethod
class AbstractFactory(metaclass=ABCMeta):
"""
抽象工厂,定义所有工厂需要实现的接口
"""
@abstractmethod
def make_object(self):
pass
class SquareFactory(AbstractFactory):
"""
具体工厂,继承抽象工厂,实现必要接口
"""
def make_object(self):
return Square()
class CircleFactory(AbstractFactory):
"""
具体工厂,继承抽象工厂,实现必要接口
"""
def make_object(self):
return Circle()
class Square:
@staticmethod
def draw():
return "I am a Square"
class Circle:
@staticmethod
def draw():
return "I am a Circle"
if __name__ == '__main__':
def draw_func(factory):
"""
调用函数,不关心具体工厂,直接使用make_object()接口创建对象。
"""
obj = factory.make_object()
print(obj.draw())
factory = SquareFactory()
draw_func(factory)
factory = CircleFactory()
draw_func(factory)