当前位置: 首页 > article >正文

设计模式大全和详解,含Python代码例子

若有不理解,可以问一下这几个免费的AI网站

  • https://ai-to.cn/chat
  • http://m6z.cn/6arKdN
  • http://m6z.cn/6b1quh
  • http://m6z.cn/6wVAQG
  • http://m6z.cn/63vlPw

下面是设计模式的简要介绍和 Python 代码示例,涵盖主要的创建型、结构型和行为型模式。

一、创建型模式

1. 单例模式 (Singleton)

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

class Singleton:
    _instance = None

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

s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # 输出: True
2. 工厂方法模式 (Factory Method)

定义一个接口用于创建对象,让子类决定实例化哪一个类。

class Animal:
    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()

factory = AnimalFactory()
dog = factory.create_animal("dog")
print(dog.speak())  # 输出: Woof!
3. 抽象工厂模式 (Abstract Factory)

提供一个接口用于创建一系列相关或依赖的对象。

class AbstractFactory:
    def create_animal(self):
        pass
    
    def create_vehicle(self):
        pass

class DogFactory(AbstractFactory):
    def create_animal(self):
        return Dog()
    
    def create_vehicle(self):
        return DogSled()

class DogSled:
    def ride(self):
        return "Riding a dog sled!"

factory = DogFactory()
dog = factory.create_animal()
sled = factory.create_vehicle()
print(dog.speak())  # 输出: Woof!
print(sled.ride())  # 输出: Riding a dog sled!
4. 建造者模式 (Builder)

将一个复杂对象的构建与它的表示分离。

class Car:
    def __init__(self):
        self.model = None
        self.color = None

class CarBuilder:
    def __init__(self):
        self.car = Car()

    def set_model(self, model):
        self.car.model = model
        return self

    def set_color(self, color):
        self.car.color = color
        return self

    def build(self):
        return self.car

builder = CarBuilder()
car = builder.set_model("Toyota").set_color("Red").build()
print(car.model, car.color)  # 输出: Toyota Red
5. 原型模式 (Prototype)

通过复制现有的实例来创建新的实例。

import copy

class Prototype:
    def __init__(self):
        self._objects = {}

    def register_object(self, name, obj):
        self._objects[name] = obj

    def unregister_object(self, name):
        del self._objects[name]

    def clone(self, name, **attrs):
        obj = copy.deepcopy(self._objects.get(name))
        obj.__dict__.update(attrs)
        return obj

class Car:
    def __init__(self):
        self.model = "Base Model"

prototype = Prototype()
prototype.register_object("car1", Car())

car_clone = prototype.clone("car1", model="Clone Model")
print(car_clone.model)  # 输出: Clone Model

二、结构型模式

1. 适配器模式 (Adapter)

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

class EuropeanPlug:
    def connect(self):
        return "Connected to European plug."

class USAToEuropeanAdapter:
    def __init__(self, usa_plug):
        self.usa_plug = usa_plug

    def connect(self):
        return self.usa_plug.connect() + " (adapted to European plug)"

class USAPlug:
    def connect(self):
        return "Connected to USA plug."

usa_plug = USAPlug()
adapter = USAToEuropeanAdapter(usa_plug)
print(adapter.connect())  # 输出: Connected to USA plug. (adapted to European plug)
2. 桥接模式 (Bridge)

将抽象部分与实现部分分离,使它们可以独立变化。

class Color:
    def fill(self):
        pass

class Red(Color):
    def fill(self):
        return "Filled with red color."

class Green(Color):
    def fill(self):
        return "Filled with green color."

class Shape:
    def __init__(self, color):
        self.color = color

class Circle(Shape):
    def draw(self):
        return f"Drawing a circle. {self.color.fill()}"

circle = Circle(Red())
print(circle.draw())  # 输出: Drawing a circle. Filled with red color.
3. 组合模式 (Composite)

将对象组合成树形结构以表示“部分-整体”的层次结构。

class Component:
    def operation(self):
        pass

class Leaf(Component):
    def operation(self):
        return "Leaf"

class Composite(Component):
    def __init__(self):
        self.children = []

    def add(self, component):
        self.children.append(component)

    def operation(self):
        results = [child.operation() for child in self.children]
        return "Composite: " + ", ".join(results)

composite = Composite()
composite.add(Leaf())
composite.add(Leaf())
print(composite.operation())  # 输出: Composite: Leaf, Leaf
4. 装饰模式 (Decorator)

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

class Coffee:
    def cost(self):
        return 5

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

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

coffee = Coffee()
print(coffee.cost())  # 输出: 5

coffee_with_milk = MilkDecorator(coffee)
print(coffee_with_milk.cost())  # 输出: 6
5. 外观模式 (Facade)

为一个复杂子系统提供一个简单的接口。

class CPU:
    def freeze(self):
        print("CPU freezing.")

class Memory:
    def load(self):
        print("Memory loading.")

class HardDrive:
    def read(self):
        print("Hard drive reading.")

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

    def start(self):
        self.cpu.freeze()
        self.memory.load()
        self.hard_drive.read()
        print("Computer started.")

computer = Computer()
computer.start()  # 输出: CPU freezing. Memory loading. Hard drive reading. Computer started.
6. 享元模式 (Flyweight)

通过共享大量细粒度的对象来减少内存消耗。

class Flyweight:
    def __init__(self, intrinsic_state):
        self.intrinsic_state = intrinsic_state

class FlyweightFactory:
    def __init__(self):
        self.flyweights = {}

    def get_flyweight(self, key):
        if key not in self.flyweights:
            self.flyweights[key] = Flyweight(key)
        return self.flyweights[key]

factory = FlyweightFactory()
flyweight1 = factory.get_flyweight("shared")
flyweight2 = factory.get_flyweight("shared")
print(flyweight1 is flyweight2)  # 输出: True
7. 代理模式 (Proxy)

为其他对象提供一种代理以控制对这个对象的访问。

class RealSubject:
    def request(self):
        return "Real subject request."

class Proxy:
    def __init__(self, real_subject):
        self.real_subject = real_subject

    def request(self):
        print("Proxy: Pre-processing.")
        return self.real_subject.request()

real_subject = RealSubject()
proxy = Proxy(real_subject)
print(proxy.request())  # 输出: Proxy: Pre-processing. Real subject request.

三、行为型模式

1. 链式责任模式 (Chain of Responsibility)

使多个对象都有机会处理请求。

class Handler:
    def set_next(self, handler):
        self.next_handler = handler
        return handler

    def handle(self, request):
        if hasattr(self, 'next_handler'):
            return self.next_handler.handle(request)
        return None

class ConcreteHandlerA(Handler):
    def handle(self, request):
        if request == "A":
            return "Handler A processed the request."
        return super().handle(request)

class ConcreteHandlerB(Handler):
    def handle(self, request):
        if request == "B":
            return "Handler B processed the request."
        return super().handle(request)

handler_a = ConcreteHandlerA()
handler_b = ConcreteHandlerB()
handler_a.set_next(handler_b)

print(handler_a.handle("A"))  # 输出: Handler A processed the request.
print(handler_a.handle("B"))  # 输出: Handler B processed the request.
2. 命令模式 (Command)

将请求封装为一个对象。

class Command:
    def execute(self):
        pass

class Light:
    def turn_on(self):
        return "Light is ON"

    def turn_off(self):
        return "Light is OFF"

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

    def execute(self):
        return self.light.turn_on()

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

    def execute(self):
        return self.light.turn_off()

light = Light()
on_command = LightOnCommand(light)
off_command = LightOffCommand(light)

print(on_command.execute())  # 输出: Light is ON
print(off_command.execute())  # 输出: Light is OFF
3. 解释器模式 (Interpreter)

定义一个语言的文法,并提供解释器。

class Expression:
    def interpret(self):
        pass

class TerminalExpression(Expression):
    def __init__(self, data):
        self.data = data

    def interpret(self):
        return f"Interpreting {self.data}"

class OrExpression(Expression):
    def __init__(self, expr1, expr2):
        self.expr1 = expr1
        self.expr2 = expr2

    def interpret(self):
        return f"{self.expr1.interpret()} or {self.expr2.interpret()}"

expr1 = TerminalExpression("A")
expr2 = TerminalExpression("B")
or_expr = OrExpression(expr1, expr2)
print(or_expr.interpret())  # 输出: Interpreting A or Interpreting B
4. 迭代器模式 (Iterator)

提供一种方法顺序访问一个集合对象中的各个元素。

class Iterator:
    def __init__(self, collection):
        self._collection = collection
        self._index = 0

    def __next__(self):
        if self._index < len(self._collection):
            result = self._collection[self._index]
            self._index += 1
            return result
        raise StopIteration

class Collection:
    def __init__(self):
        self.items = []

    def add(self, item):
        self.items.append(item)

    def __iter__(self):
        return Iterator(self.items)

collection = Collection()
collection.add("Item 1")
collection.add("Item 2")

for item in collection:
    print(item)  # 输出: Item 1 \n Item 2
5. 中介者模式 (Mediator)

定义一个对象来封装一系列的对象交互。

class Mediator:
    def notify(self, sender, event):
        pass

class ConcreteMediator(Mediator):
    def __init__(self, component1, component2):
        self.component1 = component1
        self.component2 = component2
        self.component1.mediator = self
        self.component2.mediator = self

    def notify(self, sender, event):
        if event == "A":
            print("Mediator reacts on A and triggers following operations:")
            self.component2.do_c()

class Component1:
    def __init__(self):
        self.mediator = None

    def do_a(self):
        print("Component 1 does A.")
        self.mediator.notify(self, "A")

class Component2:
    def __init__(self):
        self.mediator = None

    def do_c(self):
        print("Component 2 does C.")

component1 = Component1()
component2 = Component2()
mediator = ConcreteMediator(component1, component2)

component1.do_a()  # 输出: Component 1 does A. Mediator reacts on A and triggers following operations: Component 2 does C.
6. 备忘录模式 (Memento)

在不违反封装性的前提下,捕获一个对象的内部状态。

class Memento:
    def __init__(self, state):
        self.state = state

class Originator:
    def __init__(self):
        self.state = None

    def create_memento(self):
        return Memento(self.state)

    def restore(self, memento):
        self.state = memento.state

originator = Originator()
originator.state = "State 1"
memento = originator.create_memento()

originator.state = "State 2"
originator.restore(memento)
print(originator.state)  # 输出: State 1
7. 发布-订阅模式 (Observer)

定义了一种一对多的依赖关系,让多个观察者同时监听。

class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        self._observers.append(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"Observer received message: {message}")

subject = Subject()
observer1 = ConcreteObserver()
subject.attach(observer1)

subject.notify("Hello Observers!")  # 输出: Observer received message: Hello Observers!
8. 状态模式 (State)

允许对象在内部状态变化时改变它的行为。

class State:
    def handle(self):
        pass

class ConcreteStateA(State):
    def handle(self):
        return "State A handling."

class ConcreteStateB(State):
    def handle(self):
        return "State B handling."

class Context:
    def __init__(self):
        self.state = ConcreteStateA()

    def request(self):
        print(self.state.handle())
        self.state = ConcreteStateB() if isinstance(self.state, ConcreteStateA) else ConcreteStateA()

context = Context()
context.request()  # 输出: State A handling.
context.request()  # 输出: State B handling.
9. 策略模式 (Strategy)

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

class Strategy:
    def execute(self, a, b):
        pass

class AddStrategy(Strategy):
    def execute(self, a, b):
        return a + b

class SubtractStrategy(Strategy):
    def execute(self, a, b):
        return a - b

class Context:
    def __init__(self, strategy):
        self.strategy = strategy

    def execute_strategy(self, a, b):
        return self.strategy.execute(a, b)

context = Context(AddStrategy())
print(context.execute_strategy(5, 3))  # 输出: 8

context.strategy = SubtractStrategy()
print(context.execute_strategy(5, 3))  # 输出: 2
10. 访问者模式 (Visitor)

表示一个作用于某种对象结构中的各元素的操作。

class Visitor:
    def visit(self, element):
        pass

class ConcreteVisitor(Visitor):
    def visit(self, element):
        return f"Visited {element.name}"

class Element:
    def __init__(self, name):
        self.name = name

    def accept(self, visitor):
        return visitor.visit(self)

elements = [Element("Element 1"), Element("Element 2")]
visitor = ConcreteVisitor()

for element in elements:
    print(element.accept(visitor))  # 输出: Visited Element 1 \n Visited Element 2

总结

设计模式是软件开发中常用的解决方案,理解这些模式及其实现能够帮助开发者更高效地解决问题。Python 提供了灵活的语法,使得实现这些模式变得相对简单。选择合适的设计模式和场景能够提高代码的可维护性和可读性。


http://www.kler.cn/a/294839.html

相关文章:

  • MyBatis CRUD快速入门
  • AtomicInteger 和 AtomicIntegerFieldUpdater的区别
  • 小面馆叫号取餐流程 佳易王面馆米线店点餐叫号管理系统操作教程
  • LeetCode【0014】最长公共前缀
  • Rust学习(二):rust基础语法Ⅰ
  • Ai创作新风标!仅需三步,利用ai工具免费制作抖音爆款的动物融合视频(含完整的步骤)
  • 基于“SRP模型+”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用
  • 编写vue的输入框的自定义指令研究
  • 力扣9.7
  • 最新版 Java 网络编程经典案例:IM 系统、网络拷贝|万字笔记
  • 软件工程-图书管理系统的概要设计
  • 网络层ip协议
  • echarts 水平柱图 科技风
  • 单北斗新时代,遨游通讯四款防爆手机筑牢安全防线
  • Java数组(详解版)
  • Windows .NET8 实现 远程一键部署,几秒完成发布,提高效率 - CICD
  • Rust : 从事量化的生态现状与前景
  • 漫谈设计模式 [17]:状态模式
  • 调研-libevent
  • VitePress 自定义 CSS 指南
  • docker基础命令总结
  • 流程图符号速查:快速掌握流程图绘制要点
  • Kafka【十二】消费者拉取主题分区的分配策略
  • NISP 一级 —— 考证笔记合集
  • RISC-V (十二)系统调用
  • python网络爬虫(五)——爬取天气预报