23种设计模式Python版

创建型模式

简单工厂模式

在这里插入图片描述

  • 实现
from abc import abstractmethod, ABCMeta

class Product(metaclass = ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def do(self):
        pass

class ConcreteProductA(Product):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductA]do()")

class ConcreteProductB(Product):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductB]do()")

class SimpleFactory:
    @staticmethod
    def create_product(arg):
        if "A" == str.upper(arg):
            return ConcreteProductA()
        elif "B" == str.upper(arg):
            return ConcreteProductB()
        else:
            raise Exception(f"Unsupported: {
     
     arg}")
        
if __name__ == "__main__":
    product_a = SimpleFactory.create_product("A")
    product_a.do()

    product_b = SimpleFactory.create_product("b")
    product_b.do()

  • 优点
    简单工厂模式提供了专门的工厂类用于创建对象,将对象的创建和对象的使用分离开。客户端只需提供想要的产品属性,简单工厂就可以创建出来具体的产品供客户端使用(客户端不用关心创建逻辑)。
  • 缺点
    工厂类集中了所有产品的创建逻辑,职责过重,一旦不能正常工作,整个系统都要受到影响。系统扩展困难,一旦添加新产品就得修改工厂逻辑,在产品类型较多时,有可能造成工厂逻辑过于复杂,不利于系统的扩展和维护。
  • 适用场景
    工厂类负责创建的对象比较少,不会造成工厂方法中的业务逻辑太过复杂。

工厂方法模式

在这里插入图片描述

  • 实现
from abc import abstractmethod, ABCMeta

class Product(metaclass = ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def do(self):
        pass

class ConcreteProductA(Product):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductA]do()")

class ConcreteProductB(Product):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductB]do()")

class Factory(metaclass = ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def create_product(self):
        pass

class FactoryA(Factory):
    def __init__(self):
        super().__init__()

    def create_product(self):
        return ConcreteProductA()

class FactoryB(Factory):
    def __init__(self):
        super().__init__()

    def create_product(self):
        return ConcreteProductB()
        
if __name__ == "__main__":
    factoryA = FactoryA()
    productA = factoryA.create_product()
    productA.do()

    factoryB = FactoryB()
    productB = factoryB.create_product()
    productB.do()
  • 优点
    继承了简单工厂模式的优点,用户只需要关心所需产品对应的工厂。扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以,符合“开闭原则”。

  • 缺点
    每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度。

  • 使用场景
    数据库访问,当用户不知道最后系统采用哪一类数据库,以及数据库可能有变化时。

抽象工厂模式

在这里插入图片描述
产品族:小米的手机+电视、华为的手机+电视
产品等级结构:手机的小米+华为,电视的小米+华为
增加产品族,比如OPPO的手机+电视,只需增加OPPO工厂及对应具体产品即可,符合“开闭原则”;但增加产品等级结构,比如耳机的小米+华为,就需要修改所有工厂,违反“开闭原则”。

from abc import abstractmethod, ABCMeta

class ProductA(metaclass = ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def do(self):
        pass

class ConcreteProductA1(ProductA):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductA1]do()")

class ConcreteProductA2(ProductA):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductA2]do()")

class ProductB(metaclass = ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def do(self):
        pass

class ConcreteProductB1(ProductB):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductB1]do()")

class ConcreteProductB2(ProductB):
    def __init__(self):
        super().__init__()

    def do(self):
        print("[ConcreteProductB2]do()")

class Factory(metaclass = ABCMeta):
    def __init__(self):
        pass

    @abstractmethod
    def create_productA(self):
        pass

    @abstractmethod
    def create_productB(self):
        pass

class Factory1(Factory):
    def __init__(self):
        super().__init__()

    def create_productA(self):
        return ConcreteProductA1()
    
    def create_productB(self):
        return ConcreteProductB1()

class Factory2(Factory):
    def __init__(self):
        super().__init__()

    def create_productA(self):
        return ConcreteProductA2()
    
    def create_productB(self):
        return ConcreteProductB2()
        
if __name__ == "__main__":
    factory1 = Factory1()
    productA1 = factory1.create_productA()
    productB1 = factory1.create_productB()
    productA1.do()
    productB1.do()

    factory2 = Factory2()
    productA2 = factory2.create_productA()
    productB2 = factory2.create_productB()
    productA2.do()
    productB2.do()

单例模式

在这里插入图片描述

class Singleton:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance
        
if __name__ == "__main__":
    singleton1 = Singleton(1, x = 1)
    singleton2 = Singleton(2, x = 2)
    print(id(singleton1) == id(singleton2))

原型模式

在这里插入图片描述
浅克隆
在这里插入图片描述

深克隆
在这里插入图片描述

from abc import ABCMeta, abstractmethod
import copy

class Prototype(metaclass = ABCMeta):
    @abstractmethod
    def clone(self):
        pass

class PrototypeA(Prototype):
    def clone(self):
        return copy.copy(self)
    
class PrototypeB(Prototype):
    def clone(self):
        return copy.copy(self)
        
if __name__ == "__main__":
    prototypeA = PrototypeA()
    prototypeACopy = prototypeA.clone()

建造者模式

在这里插入图片描述

from abc import ABCMeta, abstractmethod

class Product:
    def __init__(self, a = None, b = None, c = None):
        self.a = a
        self.b = b
        self.c = c

    def __str__(self):
        return f"Product[a={
     
     self.a}, b={
     
     self.b}, c={
     
     self.c}]"

class Builder(metaclass = ABCMeta):
    @abstractmethod
    def buildA(self):
        pass

    @abstractmethod
    def buildB(self):
        pass

    @abstractmethod
    def buildC(self):
        pass

    @abstractmethod
    def getResult(self):
        pass

class ConcreteBuilder(Builder):
    def __init__(self):
        self.product = Product()

    def buildA(self):
        self.product.a = 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值