类工厂模式(Factory Pattern)

工厂模式(Factory Pattern)是一种常用的设计模式,用于创建对象时不会将客户端代码与类构造代码直接关联起来,而是通过一个共同的接口指向新创建的对象。这样可以在不修改客户端代码的情况下更改所创建的具体类实例。在Python中,实现工厂模式可以通过多种方式,包括简单工厂、工厂方法模式、抽象工厂模式等。

1. 简单工厂模式

简单工厂模式通常通过一个静态方法来创建对象,这个静态方法接收一个参数(通常是类名或其他标识符),然后根据这个参数返回相应的类实例。

class ProductA:
    def operation(self):
        return "Result of the Product A"

class ProductB:
    def operation(self):
        return "Result of the Product B"

class Factory:
    @staticmethod
    def get_product(product_type):
        if product_type == "A":
            return ProductA()
        elif product_type == "B":
            return ProductB()
        else:
            raise ValueError("Unsupported product type")

# 使用
productA = Factory.get_product("A")
print(productA.operation())

productB = Factory.get_product("B")
print(productB.operation())

2. 工厂方法模式

工厂方法模式将对象的创建延迟到子类中进行。工厂方法让类的实例化推迟到子类中进行。

class Product:
    def operation(self):
        pass

class ConcreteProductA(Product):
    def operation(self):
        return "Result of the ConcreteProduct A"

class ConcreteProductB(Product):
    def operation(self):
        return "Result of the ConcreteProduct B"

class Creator:
    def factory_method(self):
        raise NotImplementedError("Subclass must implement abstract method")

    def an_operation(self):
        product = self.factory_method()
        return product.operation()

class ConcreteCreatorA(Creator):
    def</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值