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
相关推荐
三川69817 分钟前
Tkinter库的学习记录08- 容器控件
python
c_lb728822 分钟前
近期AI量化工具选择,学习开发执行要分开
人工智能·python
天天进步201527 分钟前
Python全栈项目--校园食堂点餐与推荐系统
开发语言·python
Ulyanov30 分钟前
雷达导引头体制演进、技术特点与数学模型
python·雷达电子对抗·导引头
eybk44 分钟前
写一个可以编制pdf文件的python程序
开发语言·python·pdf
卷无止境1 小时前
从Python的cryptography库出发,从零开始理解密码学,到构建零信任网络
后端·python
YFJ_mily1 小时前
**Python 实战:写一个论文 PDF 投稿自检工具|附 IPAT 2026 智能光子学会议征稿信息
人工智能·python·pdf·量子计算·论文投稿·智能光子学
三川6981 小时前
Tkinter库的学习记录05-文本框Entry
python
cui_ruicheng1 小时前
Python从入门到实战(八):封装、多态与抽象类
开发语言·python
nanawinona1 小时前
2026年AI量化工具怎么选,先定位学习开发还是执行
人工智能·python