python的设计模式

设计模式是解决软件设计中常见问题的可重用解决方案。Python 作为一种灵活且强大的编程语言,支持多种设计模式的实现。以下是 Python 中常见的几种设计模式及其示例:


1. 单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供全局访问点。

python 复制代码
class Singleton:
    _instance = None

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

# 使用
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # 输出: True

2. 工厂模式(Factory Pattern)

通过工厂类创建对象,而不是直接调用构造函数。

python 复制代码
from abc import ABC, abstractmethod

# 抽象产品
class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass

# 具体产品
class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

# 工厂类
class AnimalFactory:
    def create_animal(self, animal_type):
        if animal_type == "dog":
            return Dog()
        elif animal_type == "cat":
            return Cat()
        else:
            raise ValueError("Unknown animal type")

# 使用
factory = AnimalFactory()
dog = factory.create_animal("dog")
print(dog.speak())  # 输出: Woof!

3. 观察者模式(Observer Pattern)

定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会收到通知。

python 复制代码
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):
        for observer in self._observers:
            observer.update(self)

class Observer:
    def update(self, subject):
        pass

# 具体观察者
class ConcreteObserver(Observer):
    def update(self, subject):
        print("Subject's state has changed!")

# 使用
subject = Subject()
observer = ConcreteObserver()
subject.attach(observer)
subject.notify()  # 输出: Subject's state has changed!

4. 策略模式(Strategy Pattern)

定义一系列算法,并将它们封装在独立的类中,使它们可以互相替换。

python 复制代码
from abc import ABC, abstractmethod

# 策略接口
class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

# 具体策略
class CreditCardPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paid {amount} via Credit Card")

class PayPalPayment(PaymentStrategy):
    def pay(self, amount):
        print(f"Paid {amount} via PayPal")

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

    def execute_payment(self, amount):
        self._strategy.pay(amount)

# 使用
context = PaymentContext(CreditCardPayment())
context.execute_payment(100)  # 输出: Paid 100 via Credit Card

5. 装饰器模式(Decorator Pattern)

动态地为对象添加功能,而不改变其结构。

python 复制代码
class Coffee:
    def cost(self):
        return 5

class MilkDecorator:
    def __init__(self, coffee):
        self._coffee = coffee

    def cost(self):
        return self._coffee.cost() + 2

class SugarDecorator:
    def __init__(self, coffee):
        self._coffee = coffee

    def cost(self):
        return self._coffee.cost() + 1

# 使用
coffee = Coffee()
coffee_with_milk = MilkDecorator(coffee)
coffee_with_milk_and_sugar = SugarDecorator(coffee_with_milk)
print(coffee_with_milk_and_sugar.cost())  # 输出: 8

6. 适配器模式(Adapter Pattern)

将一个类的接口转换成客户端期望的另一个接口。

python 复制代码
class EuropeanSocket:
    def voltage(self):
        return 230

class USASocket:
    def voltage(self):
        return 120

class Adapter:
    def __init__(self, socket):
        self._socket = socket

    def voltage(self):
        if isinstance(self._socket, EuropeanSocket):
            return self._socket.voltage() / 2
        return self._socket.voltage()

# 使用
european_socket = EuropeanSocket()
adapter = Adapter(european_socket)
print(adapter.voltage())  # 输出: 115

7. 命令模式(Command Pattern)

将请求封装为对象,从而使不同的请求、队列或日志支持参数化操作。

python 复制代码
class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

class LightOnCommand(Command):
    def __init__(self, light):
        self._light = light

    def execute(self):
        self._light.on()

class Light:
    def on(self):
        print("Light is on")

# 使用
light = Light()
command = LightOnCommand(light)
command.execute()  # 输出: Light is on

8. 模板方法模式(Template Method Pattern)

定义一个算法的框架,允许子类在不改变结构的情况下重写某些步骤。

python 复制代码
from abc import ABC, abstractmethod

class Game(ABC):
    def play(self):
        self.initialize()
        self.start()
        self.end()

    @abstractmethod
    def initialize(self):
        pass

    @abstractmethod
    def start(self):
        pass

    @abstractmethod
    def end(self):
        pass

class Chess(Game):
    def initialize(self):
        print("Chess game initialized")

    def start(self):
        print("Chess game started")

    def end(self):
        print("Chess game ended")

# 使用
chess = Chess()
chess
相关推荐
旧时光巷9 分钟前
【Flask 基础 ①】 | 路由、参数与模板渲染
后端·python·零基础·flask·web·模板渲染·路由系统
java1234_小锋18 分钟前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博评论IP地图可视化分析实现
python·自然语言处理·flask
golitter.32 分钟前
python的异步、并发开发
开发语言·python
陈敬雷-充电了么-CEO兼CTO1 小时前
强化学习三巨头PK:PPO、GRPO、DPO谁是大模型训练的「王炸」?
人工智能·python·机器学习·chatgpt·aigc·ppo·grpo
SiYuanFeng2 小时前
【问题未解决-寻求帮助】VS Code 中使用 Conda 环境,运行 Python 后 PowerShell 终端输出内容立即消失
开发语言·python·conda
段ヤシ.2 小时前
Windows环境下安装Python和PyCharm
开发语言·python·pycharm
测试19983 小时前
Newman+Jenkins实施接口自动化测试
自动化测试·软件测试·python·测试工具·职场和发展·jenkins·测试用例
feuiw4 小时前
django-3模型操作
python·django
计算机毕设定制辅导-无忧学长4 小时前
InfluxDB 与 Python 框架结合:Django 应用案例(一)
python·django·sqlite
Estrella_4 小时前
解决pd.cut后groupby出现的警告:深入理解observed参数
python