工厂模式是一种设计模式,它属于创建型模式。这种模式提供了一种创建对象的最佳方式,而不需要暴露创建逻辑的细节。工厂模式主要分为两种类型:简单工厂模式和工厂方法模式。

工厂模式的特点

  • 封装性:工厂模式将对象的创建和对象的使用分离,降低了模块间的耦合度。
  • 扩展性:当需要添加新的产品类时,只需要添加相应的工厂类即可,无需修改现有的代码。
  • 复用性:通过工厂类创建对象,提高了代码的复用性。

简单工厂模式

简单工厂模式是一种最简单的工厂模式,它只有一个工厂类,负责创建所有产品的实例。

class Product:
    def use(self):
        pass

class ConcreteProductA(Product):
    def use(self):
        print("使用产品A")

class ConcreteProductB(Product):
    def use(self):
        print("使用产品B")

class SimpleFactory:
    def create_product(self, type):
        if type == "A":
            return ConcreteProductA()
        elif type == "B":
            return ConcreteProductB()
        else:
            raise ValueError("未知的产品类型")

# 使用
simple_factory = SimpleFactory()
product_a = simple_factory.create_product("A")
product_a.use()

工厂方法模式

工厂方法模式是一种更加灵活的工厂模式,它定义了一个用于创建对象的接口,让子类决定实例化哪一个类。

class Product:
    def use(self):
        pass

class ConcreteProductA(Product):
    def use(self):
        print("使用产品A")

class ConcreteProductB(Product):
    def use(self):
        print("使用产品B")

class Creator:
    def create_product(self):
        pass

class ConcreteCreatorA(Creator):
    def create_product(self):
        return ConcreteProductA()

class ConcreteCreatorB(Creator):
    def create_product(self):
        return ConcreteProductB()

# 使用
creator_a = ConcreteCreatorA()
product_a = creator_a.create_product()
product_a.use()

creator_b = ConcreteCreatorB()
product_b = creator_b.create_product()
product_b.use()

更多内容

如果您想了解更多关于工厂模式的内容,请访问我们的设计模式教程。


Factory Pattern Example