工厂方法模式是一种对象创建型设计模式,它提供了一种创建对象的最佳方式,而不需要暴露对象的类细节。

模式结构

  • 抽象工厂(Abstract Factory):定义创建对象的接口,但不实现它。
  • 具体工厂(Concrete Factory):实现抽象工厂接口,创建具体对象。
  • 产品(Product):定义由工厂创建的对象的接口。
  • 具体产品(Concrete Product):实现产品接口,代表具体创建的对象。

例子

假设我们要创建一个图形库,其中包括圆形、正方形和三角形。我们可以使用工厂方法模式来创建这些图形。

### 圆形工厂

```python
class CircleFactory:
    def create_shape(self):
        return Circle()

正方形工厂

class SquareFactory:
    def create_shape(self):
        return Square()

三角形工厂

class TriangleFactory:
    def create_shape(self):
        return Triangle()

产品类

class Shape:
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        print("Drawing Circle")

class Square(Shape):
    def draw(self):
        print("Drawing Square")

class Triangle(Shape):
    def draw(self):
        print("Drawing Triangle")

使用工厂

def main():
    circle_factory = CircleFactory()
    square_factory = SquareFactory()
    triangle_factory = TriangleFactory()

    circle = circle_factory.create_shape()
    square = square_factory.create_shape()
    triangle = triangle_factory.create_shape()

    circle.draw()
    square.draw()
    triangle.draw()

if __name__ == "__main__":
    main()

更多关于设计模式的例子,请访问设计模式示例

Circle
Square
Triangle