常用设计模式

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

相关推荐
七月丶8 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞9 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼9 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室1 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式