简单工厂模式是一种创建型设计模式,它提供了一种统一的方式来创建对象,而不需要直接实例化对象。在简单工厂模式中,我们定义一个工厂类,该工厂类负责根据客户端的请求创建对象。

下面是一个简单工厂模式的示例代码:

class Product:
    def __init__(self, name):
        self.name = name

    def operation(self):
        pass

class ConcreteProductA(Product):
    def operation(self):
        print('ConcreteProductA operation')

class ConcreteProductB(Product):
    def operation(self):
        print('ConcreteProductB operation')

class SimpleFactory:
    @staticmethod
    def create_product(product_type):
        if product_type == 'A':
            return ConcreteProductA('Product A')
        elif product_type == 'B':
            return ConcreteProductB('Product B')
        else:
            raise ValueError('Invalid product type')

# 客户端代码
product_a = SimpleFactory.create_product('A')
product_a.operation()

product_b = SimpleFactory.create_product('B')
product_b.operation()

在上述示例中,我们定义了一个抽象产品类 Product,以及两个具体产品类 ConcreteProductA 和 ConcreteProductB,它们继承自抽象产品类。工厂类 SimpleFactory 通过静态方法 create_product 根据客户端传入的产品类型创建相应的产品对象。

在客户端代码中,我们通过调用 SimpleFactory.create_product 方法来创建具体产品对象,并调用其 operation 方法来执行相应的操作。

简单工厂模式的优点是将对象的创建和使用分离,客户端不需要知道具体产品的创建细节,只需要调用工厂类的方法即可。缺点是当需要新增产品时,需要修改工厂类的代码,违反了开闭原则。

Python 简单工厂模式详解:示例代码与优缺点

原文地址: https://www.cveoy.top/t/topic/qfS1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录