常用设计模式

标题:用Python实现常用设计模式:优化代码重用和可维护性

摘要:设计模式是一种解决软件设计问题的通用模板,能够提供工作效率和代码可维护性的提升。本文将介绍常用的设计模式,并使用Python语言来实现这些模式。

1. 设计模式概述

设计模式是一套被广泛验证的解决特定问题的重复使用方案。它们有助于提高代码的可重用性、可维护性和扩展性。常见的设计模式包括创建型模式、结构型模式和行为型模式。

2. 创建型模式

2.1. 单例模式(Singleton Pattern)

单例模式用于确保类只有一个实例,并提供一个全局访问点。以下是Python中实现单例模式的示例代码:

python 复制代码
class Singleton:
    instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.instance:
            cls.instance = super().__new__(cls, *args, **kwargs)
        return cls.instance

2.2. 工厂模式(Factory Pattern)

工厂模式用于根据不同的条件创建不同的对象。以下是Python中实现工厂模式的示例代码:

python 复制代码
class Shape:
    def draw(self):
        pass

class Circle(Shape):
    def draw(self):
        print("绘制圆形")

class Rectangle(Shape):
    def draw(self):
        print("绘制矩形")

class ShapeFactory:
    def createShape(self, shapeType):
        if shapeType == 'Circle':
            return Circle()
        elif shapeType == 'Rectangle':
            return Rectangle()

shapeFactory = ShapeFactory()
circle = shapeFactory.createShape('Circle')
circle.draw()  # 输出:绘制圆形

3. 结构型模式

3.1. 适配器模式(Adapter Pattern)

适配器模式用于在不兼容的接口之间进行适配。以下是Python中实现适配器模式的示例代码:

python 复制代码
class Adaptee:
    def specific_request(self):
        return "适配者的特殊请求"

class Target:
    def request(self):
        return "目标的普通请求"

class Adapter(Target):
    def __init__(self, adaptee):
        self.adaptee = adaptee

    def request(self):
        return f"{self.adaptee.specific_request()},已经适配过了"

adaptee = Adaptee()
adapter = Adapter(adaptee)
adapter.request()  # 输出:适配者的特殊请求,已经适配过了

3.2. 装饰器模式(Decorator Pattern)

装饰器模式用于在不改变接口的情况下,动态地添加或修改对象的行为。以下是Python中实现装饰器模式的示例代码:

python 复制代码
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.add_behavior()

    def add_behavior(self):
        print("添加额外的行为")

component = ConcreteComponent()
decorator = ConcreteDecorator(component)
decorator.operation()  # 输出:执行原始操作 添加额外的行为

4. 行为型模式

4.1. 观察者模式(Observer Pattern)

观察者模式用于建立对象之间的一对多依赖关系,当一个对象状态改变时,其依赖对象将自动收到通知。以下是Python中实现观察者模式的示例代码:

python 复制代码
class Subject:
    def __init__(self):
        self.observers = []

    def register(self, observer):
        self.observers.append(observer)

    def unregister(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 ConcreteObserver(Observer):
    def update(self, message):
        print(f"收到通知:{message}")

subject = Subject()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
subject.register(observer1)
subject.register(observer2)
subject.notify("新消息")  # 输出:收到通知:新消息

4.2. 策略模式(Strategy Pattern)

策略模式用于封装一系列算法,它们可以相互替换,使得算法的变化独立于使用该算法的客户端。以下是Python中实现策略模式的示例代码:

python 复制代码
class Context:
    def __init__(self, strategy):
        self.strategy = strategy

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

class Strategy:
    def execute(self):
        pass

class ConcreteStrategyA(Strategy):
    def execute(self):
        print("执行策略A")

class ConcreteStrategyB(Strategy):
    def execute(self):
        print("执行策略B")

strategyA = ConcreteStrategyA()
contextA = Context(strategyA)
contextA.execute_strategy()  # 输出:执行策略A

strategyB = ConcreteStrategyB()
contextB = Context(strategyB)
contextB.execute_strategy()  # 输出:执行策略B

5. 总结

本文介绍了常见的设计模式,并提供了使用Python语言实现这些模式的示例代码。这些设计模式可以提高代码的可重用性、可维护性和可扩展性,帮助开发者更加高效地解决软件设计问题。阅读本文后,希望读者能够对常用设计模式有更深入的理解,并能在实际项目中合理应用。

相关推荐
Zane19944 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫5 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19945 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19946 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..6 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1506 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)7 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki8 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅668 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa8 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio