打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python常用设计模式
userphoto

2023.08.29 广东

关注
Python 是一种多范式的编程语言,它支持多种设计模式。设计模式是一种被广泛应用于软件开发中的解决方案,它提供了一套经过验证的设计思想和方法,用于解决常见的设计问题。
下面介绍几种常见的设计模式:
1、单例模式(Singleton Pattern):确保一个类只有一个实例,并提供全局访问点。
class CEO:    _instance = None    def __init__(self, name):        self.name = name    @classmethod    def get_instance(cls, name):        if not cls._instance:            cls._instance = CEO(name)        return cls._instance# 创建 CEO 实例ceo1 = CEO.get_instance('John')print(ceo1.name)  # 输出: John# 尝试创建另一个 CEO 实例ceo2 = CEO.get_instance('Alice')print(ceo2.name)  # 输出: John,仍然是之前创建的 CEO 实例# 验证 ceo1 和 ceo2 是否为同一实例print(ceo1 is ceo2)  # 输出: True
在上述代码中,我们定义了一个 CEO 类,其中包含一个私有的类变量 _instance 表示 CEO 实例。通过类方法 get_instance 来获取 CEO 实例,如果 _instance 为空,则创建一个新的 CEO 实例并将其赋值给 _instance,否则直接返回 _instance。
通过调用 CEO.get_instance() 方法,我们可以获取 CEO 实例。由于单例模式的特性,无论我们尝试多次创建 CEO 实例,实际上都会得到同一个实例对象。
输出结果将会是:

John
John
True

2、工厂模式(Factory Pattern):通过工厂类创建对象,将对象的创建与使用相分离。
lass Pen:    def __init__(self, color):        self.color = color        def write(self, text):        print(f'Write '{text}' with {self.color} pen.')class PenFactory:    def createPen(self, color):        if color == 'red':            return Pen('red')        elif color == 'blue':            return Pen('blue')        elif color == 'green':            return Pen('green')        else:            return None# 使用工厂模式创建彩色钢笔pen_factory = PenFactory() red_pen = pen_factory.createPen('red') red_pen.write('Hello') blue_pen = pen_factory.createPen('blue') blue_pen.write('World')
在上述代码中,我们定义了一个 Pen 类,表示彩色钢笔,并具有颜色属性和写字的方法。然后我们创建了一个 PenFactory 工厂类,其中的 createPen 方法根据传入的颜色参数,返回相应颜色的钢笔实例。
通过调用 PenFactory 的 createPen 方法,我们可以创建不同颜色的钢笔对象,并调用钢笔对象的 write 方法进行写字操作。
输出结果将会是:
Write 'Hello' with red pen.
Write 'World' with blue pen.
3、观察者模式(Observer Pattern):定义对象之间的一对多依赖关系,当一个对象状态改变时,其所有依赖者会收到通知并自动更新。
class Subject:    def __init__(self):        self.observers = []    def attach(self, observer):        self.observers.append(observer)    def detach(self, observer):        self.observers.remove(observer)    def notify(self, message):        for observer in self.observers:            observer.update(message)class Observer:    def update(self, message):        pass# 具体的观察者类class User(Observer):    def __init__(self, name):        self.name = name    def update(self, message):        print(f'{self.name} 收到一条新消息:{message}')# 创建主题对象subject = Subject()# 创建观察者对象user1 = User('Alice') user2 = User('Bob') user3 = User('Charlie')# 将观察者绑定到主题对象subject.attach(user1) subject.attach(user2) subject.attach(user3)# 发送通知subject.notify('这是一条通知。')# 解除观察者绑定subject.detach(user2)# 再次发送通知subject.notify('这是另一条通知。')
4、装饰器模式(Decorator Pattern):动态地给对象添加新的功能或责任,同时不修改原始对象的结构。
# 原始组件接口
class Component:
def operation(self):
pass

# 具体组件类
class ConcreteComponent(Component):
def operation(self):
print('执行原始操作')

# 装饰器基类
class Decorator(Component):
def __init__(self, component):
self.component = component

def operation(self):
self.component.operation()

# 具体装饰器类
class ConcreteDecorator(Decorator):
def operation(self):
super().operation()
self.additional_operation()

def additional_operation(self):
print('执行额外操作')

# 创建具体组件对象
component = ConcreteComponent()

# 创建具体装饰器对象并将原始组件对象传入
decorator = ConcreteDecorator(component)

# 调用装饰器对象的操作方法
decorator.operation()
在上述代码中,我们首先定义了一个组件接口 Component,其中包含一个名为 operation 的方法。然后创建了一个具体组件类 ConcreteComponent,它实现了 Component 接口的 operation 方法。
接下来,我们定义了装饰器基类 Decorator,它也是一个具有 operation 方法的组件,但它持有一个组件对象,通过调用组件对象的 operation 方法来实现装饰功能。
最后,我们创建了具体装饰器类 ConcreteDecorator,它继承自 Decorator,在 operation 方法中先调用父类的 operation 方法(即原始组件的操作),然后执行自己的额外操作。
通过创建具体组件对象和具体装饰器对象,并将原始组件对象传入装饰器中,我们可以调用装饰器对象的 operation 方法来实现装饰功能。
输出结果将会是:
执行原始操作
执行额外操作
5、适配器模式(Adapter Pattern):将一个类的接口转换成客户端所期望的另一个接口,使得原本不兼容的类可以一起工作
# 目标接口
class Target:
def request(self):
pass

# 适配者类
class Adaptee:
def specific_request(self):
print('执行适配者操作')

# 适配器类
class Adapter(Target):
def __init__(self, adaptee):
self.adaptee = adaptee

def request(self):
self.adaptee.specific_request()

# 创建适配者对象
adaptee = Adaptee()

# 创建适配器对象并将适配者对象传入
adapter = Adapter(adaptee)

# 调用适配器对象的方法
adapter.request()
在上述代码中,我们首先定义了一个目标接口 Target,其中包含一个名为 request 的方法。
然后创建了一个适配者类 Adaptee,它有一个名为 specific_request 的方法,表示适配者自己的操作。
接下来,我们定义了适配器类 Adapter,它继承自目标接口 Target,并在构造函数中接收一个适配者对象。在适配器的 request 方法中,调用适配者对象的 specific_request 方法来实现对适配者的适配。
通过创建适配者对象和适配器对象,并将适配者对象传入适配器中,我们可以调用适配器对象的 request 方法来进行适配操作。适配器会将请求转发给适配者并执行适配者的操作。
输出结果将会是:
6、执行适配者操作策略模式(Strategy Pattern):定义一系列算法,将每个算法封装起来,并使它们可以互相替换,使得算法可以独立于使用它的客户端而变化。
# 策略接口
class Strategy:
def do_operation(self):
pass

# 具体策略类 A
class ConcreteStrategyA(Strategy):
def do_operation(self):
print('执行策略 A 的操作')

# 具体策略类 B
class ConcreteStrategyB(Strategy):
def do_operation(self):
print('执行策略 B 的操作')

# 上下文类
class Context:
def __init__(self, strategy):
self.strategy = strategy

def set_strategy(self, strategy):
self.strategy = strategy

def execute_strategy(self):
self.strategy.do_operation()

# 创建具体策略对象
strategy_a = ConcreteStrategyA()
strategy_b = ConcreteStrategyB()

# 创建上下文对象并将具体策略对象传入
context = Context(strategy_a)

# 执行当前策略
context.execute_strategy()

# 切换策略为策略 B
context.set_strategy(strategy_b)

# 再次执行策略
context.execute_strategy()
在上述代码中,我们首先定义了一个策略接口 Strategy,其中包含一个名为 do_operation 的方法。
然后创建了两个具体策略类 ConcreteStrategyA 和 ConcreteStrategyB,它们分别实现了 Strategy 接口的 do_operation 方法,表示不同的具体策略。
接下来,我们定义了上下文类 Context,它持有一个策略对象,并提供了设置策略和执行策略的方法。
通过创建具体策略对象和上下文对象,并将具体策略对象传入上下文中,我们可以调用上下文对象的 execute_strategy 方法来执行当前设置的策略。
输出结果将会是:
执行策略 A 的操作
执行策略 B 的操作

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
聊聊 Python 面试最常被问到的几种设计模式(下)
抽象工厂模式
2.7万 Star!最全面的 Python 设计模式集合
MVC架构模式
笔记--设计模式精解c++-GoF 23 种设计模式解析
股票量化交易回测框架pyalgotrade源码阅读(一)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服