设计模式(一)简单工厂模式_写最好的设计模式专栏

设计模式之工厂模式详解附代码

工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们定义一个用于创建对象的接口,但让子类决定实例化哪一个类。工厂方法使得一个类的实例化延迟到其子类。

一、简单工厂模式

简单工厂模式并不是GoF的种设计模式之一,但它是工厂模式的一种实现方式。它通过一个工厂类来负责创建其他类的实例。

示例代码:

class Dog:
    def speak(self):
        return &#;Woof!&#;

class Cat:
    def speak(self):
        return &#;Meow!&#;

class AnimalFactory:
    @staticmethod
    def create_animal(animal_type):
        if animal_type == &#;dog&#;:
            return Dog()
        elif animal_type == &#;cat&#;:
            return Cat()
        else:
            raise ValueError(&#;Unknown animal type&#;)

# 使用工厂创建对象
dog = AnimalFactory.create_animal(&#;dog&#;)
print(dog.speak())  # 输出: Woof!

cat = AnimalFactory.create_animal(&#;cat&#;)
print(cat.speak())  # 输出: Meow!

在这个例子中,AnimalFactory 是一个简单工厂,它根据传入的类型参数来决定创建 Dog 还是 Cat 对象。这种方式虽然简单,但在添加新类型时需要修改工厂类,违反了开闭原则。

二、工厂方法模式

工厂方法模式定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法使一个类的实例化延迟到其子类。

示例代码:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return &#;Woof!&#;

class Cat(Animal):
    def speak(self):
        return &#;Meow!&#;

class AnimalFactory(ABC):
    @abstractmethod
    def create_animal(self) -> Animal:
        pass

class DogFactory(AnimalFactory):
    def create_animal(self) -> Animal:
        return Dog()

class CatFactory(AnimalFactory):
    def create_animal(self) -> Animal:
        return Cat()

# 使用工厂创建对象
dog_factory = DogFactory()
dog = dog_factory.create_animal()
print(dog.speak())  # 输出: Woof!

cat_factory = CatFactory()
cat = cat_factory.create_animal()
print(cat.speak())  # 输出: Meow!

在这个例子中,AnimalFactory 是一个抽象工厂,它定义了一个 create_animal 方法。DogFactoryCatFactory 是具体的工厂,它们实现了 create_animal 方法来创建具体的对象。这样,当需要添加新的动物类型时,只需添加新的具体工厂类即可,无需修改现有的工厂类,符合开闭原则。

三、抽象工厂模式

抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。抽象工厂模式是工厂方法模式的升级版本。

示例代码:

from abc import ABC, abstractmethod

class AbstractFactory(ABC):
    @abstractmethod
    def create_product_a(self):
        pass

    @abstractmethod
    def create_product_b(self):
        pass

class ConcreteFactory1(AbstractFactory):
    def create_product_a(self):
        return ProductA1()

    def create_product_b(self):
        return ProductB1()

class ConcreteFactory2(AbstractFactory):
    def create_product_a(self):
        return ProductA2()

    def create_product_b(self):
        return ProductB2()

class ProductA(ABC):
    @abstractmethod
    def useful_function_a(self):
        pass

class ProductB(ABC):
    @abstractmethod
    def useful_function_b(self):
        pass

class ProductA1(ProductA):
    def useful_function_a(self):
        return &#;The result of the product A1.&#;

class ProductA2(ProductA):
    def useful_function_a(self):
        return &#;The result of the product A2.&#;

class ProductB1(ProductB):
    def useful_function_b(self):
        return &#;The result of the product B1.&#;

class ProductB2(ProductB):
    def useful_function_b(self):
        return &#;The result of the product B2.&#;

# 客户端代码
def client_code(factory: AbstractFactory):
    product_a = factory.create_product_a()
    product_b = factory.create_product_b()
    print(f&#;{product_a.useful_function_a()}&#;)
    print(f&#;{product_b.useful_function_b()}&#;)

if __name__ == &#;__main__&#;:
    print(&#;Client: Testing client code with the first factory type:&#;)
    client_code(ConcreteFactory1())
    print(&#;\n&#;)
    print(&#;Client: Testing the same client code with the second factory type:&#;)
    client_code(ConcreteFactory2())

在这个例子中,AbstractFactory 是一个抽象工厂,它定义了两个方法 create_product_acreate_product_bConcreteFactory1ConcreteFactory2 是具体的工厂,它们实现了这两个方法来创建具体产品。客户端代码通过调用工厂的方法来获取产品对象,而不需要知道具体的产品类是什么。这样,当需要添加新的产品系列时,只需添加新的具体工厂类即可,符合开闭原则。

原文链接:,转发请注明来源!