Python的设计模式

一、创建型模式

1.1 单例模式(Singleton)

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

适用场景:当系统中只需要一个实例时,如配置管理器、日志记录器、数据库连接池等。

python 复制代码
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance


s1 = Singleton()
s2 = Singleton()
print(s1 is s2)
# True

1.2 工厂模式(Factory)

概念:定义一个创建对象的接口,但让子类决定实例化哪个类。

适用场景:当创建逻辑复杂或需要根据不同条件创建不同对象时。

python 复制代码
from abc import ABC, abstractmethod


class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass


class Dog(Animal):
    def speak(self):
        return 'wang!'


class Cat(Animal):
    def speak(self):
        return 'miao!'


class AnimalFactory:
    def create_animal(self, animal_type: str):
        if animal_type == 'dog':
            return Dog()
        elif animal_type == 'cat':
            return Cat()
        else:
            raise ValueError("unknown animal")


factory = AnimalFactory()
dog = factory.create_animal('dog')
print(dog.speak())
# wang!

1.3 建造者模式(Builder)

概念:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

适用场景:当创建对象需要多个步骤或配置时,特别是当这些步骤可以组合出不同结果时。

python 复制代码
class Computer:
    def __init__(self):
        self.cpu = None
        self.ram = None
        self.storage = None

    def __str__(self):
        return f"Computer: CPU={self.cpu}, RAM={self.ram}, Storage={self.storage}"


class ComputerBuilder:
    def __init__(self):
        self.computer = Computer()

    def set_cpu(self, cpu):
        self.computer.cpu = cpu
        return self

    def set_ram(self, ram):
        self.computer.ram = ram
        return self

    def set_storage(self, storage):
        self.computer.storage = storage
        return self

    def build(self):
        return self.computer


builder = ComputerBuilder()
computer = builder.set_cpu("Intel i7").set_ram("16GB").set_storage("512GB SSD").build()
print(computer)
# Computer: CPU=Intel i7, RAM=16GB, Storage=512GB SSD

二.结构型模式

2.1 适配器模式 (Adapter)

概念:将一个类的接口转换成客户希望的另一个接口。

适用场景:当需要使用现有类但其接口不符合需求时。

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

    def plug(self):
        return 'European plug'


class USASocket:
    def voltage(self):
        return 120

    def plug(self):
        return 'USA plug'


class SocketAdapter:

    def __init__(self, socket):
        self.socket = socket

    def voltage(self):
        return self.socket.voltage()

    def plug(self):
        if isinstance(self.socket, EuropeanSocket):
            return 'Adapter for European plug'
        elif isinstance(self.socket, USASocket):
            return 'Adapter for USA plug'


euro_socket = EuropeanSocket()
adapter = SocketAdapter(euro_socket)
print(f'Voltage: {adapter.voltage()}V, Plug: {adapter.plug()}')

2.2 装饰器模式 (Decorator)

概念:动态地给一个对象添加一些额外的职责。

适用场景:当需要在不修改现有代码的情况下扩展功能时。

Python 复制代码
from functools import wraps
import time


def logger(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f'Calling {func.__name__} with args: {args}. kwargs: {kwargs}')
        result = func(*args, **kwargs)
        print(f'{func.__name__} returned:{result}')
        return result

    return wrapper


def timer(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f'{func.__name__} executed in {end - start_time:.4f} seconds')
        return result

    return wrapper


@logger
@timer
def calculate_sum(n):
    return sum(range(n + 1))


calculate_sum(10)
# Calling calculate_sum with args: (10,). kwargs: {}
# calculate_sum executed in 0.0000 seconds
# calculate_sum returned:55

2.3 外观模式 (Facade)

概念:为子系统中的一组接口提供一个统一的接口。

适用场景:当需要简化复杂系统的接口时。

Python 复制代码
class CPU:
    def execute(self):
        print('Executing instructions')


class Memory:
    def load(self):
        print('Loading data into memory')


class HardDrive:
    def read(self):
        print('Reading data from disk')


class ComputerFacade:
    def __init__(self):
        self.cpu = CPU()
        self.memory = Memory()
        self.hard_drive = HardDrive()

    def start(self):
        self.hard_drive.read()
        self.memory.load()
        self.cpu.execute()


computer = ComputerFacade()
computer.start()

3. 行为型模式

3.1 观察者模式 (Observer)

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

适用场景:当一个对象的状态变化需要通知其他对象时。

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 ConcreteSubject(Subject):
    def __init__(self, state):
        super().__init__()
        self._state = state

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, value):
        self._state = value
        self.notify()


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


class ConcreteObserver(Observer):
    def update(self, subject):
        print(f"Observer: Subject's state has changed to {subject.state}")


subject = ConcreteSubject('Initial state')
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()

subject.attach(observer1)
subject.attach(observer2)

subject.state = 'New state'
# Observer: Subject's state has changed to New state
# Observer: Subject's state has changed to New state

3.2 策略模式 (Strategy)

概念:定义一系列算法,将每个算法封装起来,并使它们可以互相替换。

适用场景:当需要在运行时选择算法时。

Python 复制代码
from abc import ABC, abstractmethod


class PaymentStrategy(ABC):

    @abstractmethod
    def pay(self, amount):
        pass


class CreditCardPayment(PaymentStrategy):
    def pay(self, amount):
        print(f'Paying {amount} using Credit Card')


class PayPalPayment(PaymentStrategy):

    def pay(self, amount):
        print(f'Paying {amount} using PayPal')


class ShoppingCart:
    def __init__(self):
        self._items = []
        self._payment_strategy = None

    def add_item(self, item):
        self._items.append(item)

    def set_payment_strategy(self, strategy):
        self._payment_strategy = strategy

    def checkout(self):
        total = sum(self._items)
        self._payment_strategy.pay(total)


cart = ShoppingCart()
cart.add_item(100)
cart.add_item(200)

cart.set_payment_strategy(CreditCardPayment())
cart.checkout()

cart.set_payment_strategy(PayPalPayment)
cart.checkout()
# Paying 300 using Credit Card
# Paying 300 using PayPal

3.3 命令模式 (Command)

概念:将请求封装为对象,从而允许使用不同的请求、队列或日志请求,并支持可撤销的操作。

适用场景:当需要将操作封装为对象以便参数化其他对象时。

Python 复制代码
from abc import ABC, abstractmethod


class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

    @abstractmethod
    def undo(self):
        pass


class Light:

    def on(self):
        print('Light is ON')

    def off(self):
        print('Light is OFF')


class LightOnCommand(Command):

    def __init__(self, light):
        self._light = light

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

    def undo(self):
        self._light.off()


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

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

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


class RemoteControl:

    def __init__(self):
        self._commands = []
        self._history = []

    def set_command(self, command):
        self._commands.append(command)

    def press_button(self, index):
        if 0 <= index < len(self._commands):
            command = self._commands[index]
            command.execute()
            self._history.append(command)

    def undo_last(self):
        if self._history:
            last_command = self._history.pop()
            last_command.undo()


light = Light()
light_on = LightOnCommand(light)
light_off = LightOffCommand(light)

remote = RemoteControl()
remote.set_command(light_on)
remote.set_command(light_off)

remote.press_button(0)
remote.press_button(1)
remote.undo_last()

# Light is ON
# Light is OFF
# Light is ON

3.4 模板方法模式 (Template Method)

概念:定义一个操作中的算法骨架,将一些步骤延迟到子类中。

适用场景:当多个类有相似的算法结构但某些步骤实现不同时。

Python 复制代码
from abc import ABC, abstractmethod


class DataProcessor(ABC):
    def process_data(self):
        self.load_data()
        self.clean_data()
        self.analyze_data()
        self.visualize_data()

    @abstractmethod
    def load_data(self):
        pass

    @abstractmethod
    def clean_data(self):
        pass

    def analyze_data(self):
        print("Analyzing data using default method")

    def visualize_data(self):
        print("Visualizing data using default method")


class CSVDataProcessor(DataProcessor):
    def load_data(self):
        print("Loading data from CSV file")

    def clean_data(self):
        print("Cleaning CSV data: removing duplicates")


class DatabaseDataProcessor(DataProcessor):
    def load_data(self):
        print("Loading data from database")

    def clean_data(self):
        print("Cleaning database data: handling NULL values")

    def analyze_data(self):
        print("Analyzing database data with specialized method")


csv_processor = CSVDataProcessor()
csv_processor.process_data()

print("\n")

db_processor = DatabaseDataProcessor()
db_processor.process_data()
# Loading data from CSV file
# Cleaning CSV data: removing duplicates
# Analyzing data using default method
# Visualizing data using default method
# 
# 
# Loading data from database
# Cleaning database data: handling NULL values
# Analyzing database data with specialized method
# Visualizing data using default method
相关推荐
行云流水剑7 分钟前
【学习记录】如何使用 Python 提取 PDF 文件中的内容
python·学习·pdf
心扬1 小时前
python生成器
开发语言·python
mouseliu1 小时前
python之二:docker部署项目
前端·python
狂小虎1 小时前
亲测解决self.transform is not exist
python·深度学习
Python智慧行囊1 小时前
Python 中 Django 中间件:原理、方法与实战应用
python·中间件·架构·django·开发
深科文库1 小时前
构建 MCP 服务器:第 3 部分 — 添加提示
服务器·python·chatgpt·langchain·prompt·aigc·agi
大话性能2 小时前
Mysql 百万级数据迁移实战笔记
测试
蓝婷儿2 小时前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
Mikhail_G2 小时前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析