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

news2024/9/17 3:34:40

若有不理解,可以问一下这几个免费的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.coloradmin.cn/o/2114795.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

LEAN 类型理论之注解(Annotations of LEAN Type Theory)-- 小结(Summary)

在证明LEAN类型理论的属性前&#xff0c;先对LEAN类型理论所定义的所有推演规则做一个小结&#xff0c;以便后面推导LEAN类型理论的属性。各部分的注解请查看对应文章。 注&#xff1a;这些都是在《LEAN类型理论》中截取出来的&#xff0c;具体内容&#xff0c;读者可参考该论…

ApacheKafka中的设计

文章目录 1、介绍1_Kafka&MQ场景2_Kafka 架构剖析3_分区&日志4_生产者&消费者组5_核心概念总结6_顺写&mmap7_Kafka的数据存储形式 2、Kafka的数据同步机制1_高水位&#xff08;High Watermark&#xff09;2_LEO3_高水位更新机制4_副本同步机制解析5_消息丢失问…

Redis典型应用 - 分布式锁

文章目录 目录 文章目录 1. 什么是分布式锁 2. 分布式锁的基本实现 3. 引入过期时间 4. 引入校验Id 5. 引入 watch dog(看门狗) 6. 引入redlock算法 工作原理 Redlock的优点&#xff1a; 总结 1. 什么是分布式锁 在一个分布式系统中,也可能会出现多个节点访问一个共…

QT 编译报错:C3861: ‘tr‘ identifier not found

问题&#xff1a; QT 编译报错&#xff1a;C3861&#xff1a; ‘tr’ identifier not found 原因 使用tr的地方所在的类没有继承自 QObject 类 或者在不在某一类中&#xff0c; 解决方案 就直接用类名引用 &#xff1a;QObject::tr( )

关于易优cms自定义字段不显示的问题

今天在该易优cms自定义字段&#xff0c;折腾了大半天没显示出来&#xff0c;原来是改错对方了。 主要引用的时候 要放在list标签内&#xff0c;不要看文档&#xff0c;把addfields 放在list标签上 例如 {eyou:list loop8} <li><a href"{$field.arcurl}">…

基于yolov8的电动车佩戴头盔检测系统python源码+onnx模型+评估指标曲线+精美GUI界面

【算法介绍】 基于YOLOv8的电动车佩戴头盔检测系统利用了YOLOv8这一先进的目标检测模型&#xff0c;旨在提高电动车骑行者的安全意识&#xff0c;减少因未佩戴头盔而导致的交通事故风险。YOLOv8作为YOLO系列的最新版本&#xff0c;在检测速度和精度上均进行了优化&#xff0c;…

✨机器学习笔记(一)—— 监督学习和无监督学习

1️⃣ 监督学习&#xff08;supervised learning&#xff09; ✨ 两种主要类型的监督学习问题&#xff1a; 回归&#xff08;regression&#xff09;&#xff1a;predict a number in infinitely many possible outputs. 分类&#xff08;classification&#xff09;&#xff1…

C#串口助手初级入门

1.创建项目 修改项目名称与位置&#xff0c;点击创建 2.进入界面 在视图中打开工具箱&#xff0c;鼠标拖动&#xff0c;便可以在窗口添加控件&#xff0c;右边可以查看与修改属性 3.解决方案资源管理器 发布之前&#xff0c;需要修改相关的信息&#xff0c;比如版本号&#x…

Lombok jar包引入和用法

大家好&#xff0c;今天分享一个在编写代码时的快捷方法。 当我们在封装实体类时&#xff0c;会使用set、get等一些方法。如下图&#xff0c;不但费事还影响代码的美观。 那么如何才能减少代码的冗余呢&#xff0c;首先lib中导入lombok的jar包并添加库。 此处我已导入&#xf…

插件:清理maven错误缓存.bat

插件&#xff1a;https://pan.baidu.com/s/1nHIxHoo1C4MvFlW7QbZe5Q?pwd7zenhttps://pan.baidu.com/s/1nHIxHoo1C4MvFlW7QbZe5Q?pwd7zen没错误缓存时&#xff1a; 有错误缓存时&#xff1a;

真实案例分享:零售企业如何避免销售数据的无效分析?

在零售业务的数据分析中&#xff0c;无效分析不仅浪费时间和资源&#xff0c;还可能导致错误的决策。为了避免这种情况&#xff0c;企业必须采取策略来确保他们的数据分析工作能够产生实际的商业价值。本文将通过行业内真实的案例&#xff0c;探讨零售企业如何通过精心设计的数…

springboot数据库连接由localhost改成IP以后访问报错500(2024/9/7

步骤很详细&#xff0c;直接上教程 情景复现 一.没改为IP之前正常 二.改完之后报错 问题分析 SQL没开启远程连接权限 解决方法 命令行登入数据库 mysql -u root -p切换到对应数据库 use mysql;设置root用户的连接权限允许其他IP连接数据库 update user set host % whe…

jmeter执行python脚本,python脚本的Faker库

jmeter安装 jython的插件jar包 通过如下地址下载jython-standalone-XXX.jar包并放到jmeter的XXX\lib\ext目录下面 Downloads | JythonThe Python runtime on the JVMhttps://www.jython.org/download.html 重启jmeter在JSR223中找到jython可以编写python代码执行 python造数据…

一种快速生成CSV的方法

事情是这个样子的 在QQ群在聊把如何100万数据导出成CSV文件&#xff1f;会不会很慢&#xff1f; 俺回了一句“现在的机器性能好&#xff0c;没啥问题”。 然后大家开始谈论机器的配置了。哎&#xff0c;俺的机器配置有点差。 然后俺就进行了一个测试。 测试数据 数据定义…

【C++二分查找】2439. 最小化数组中的最大值

本文涉及的基础知识点 C二分查找 LeetCode2439. 最小化数组中的最大值 给你一个下标从 0 开始的数组 nums &#xff0c;它含有 n 个非负整数。 每一步操作中&#xff0c;你需要&#xff1a; 选择一个满足 1 < i < n 的整数 i &#xff0c;且 nums[i] > 0 。 将 num…

C++ | Leetcode C++题解之第392题判断子序列

题目&#xff1a; 题解&#xff1a; class Solution { public:bool isSubsequence(string s, string t) {int n s.size(), m t.size();vector<vector<int> > f(m 1, vector<int>(26, 0));for (int i 0; i < 26; i) {f[m][i] m;}for (int i m - 1; …

.Net6/.Net8(.Net Core) IIS中部署 使用 IFormFile 上传大文件报错解决方案

描述 最近使用.Net6 WebAPI IFormFile对象接收上传文件时大于30MB(兆)的文件就会报错 原因分析 IIS上传文件有大小默认限制大约28.6MB 解决办法 .无论是Net6还是.Net8写法都一样 方法一&#xff1a;IIS可视化操作 1.打开Internet Information Services (llS)管理器&…

Banana Pi BPI-SM9 AI 计算模组采用算能科技BM1688芯片方案设计

产品概述 香蕉派 Banana Pi BPI-SM9 16-ENC-A3 深度学习计算模组搭载算能科技高集成度处理器 BM1688&#xff0c;功耗低、算力强、接口丰富、兼容性好。支持INT4/INT8/FP16/BF16/FP32混合精度计算&#xff0c;可支持 16 路高清视频实时分析&#xff0c;灵活应对图像、语音、自…

LeetCode --- 413周赛

题目列表 3274. 检查棋盘方格颜色是否相同 3275. 第 K 近障碍物查询 3276. 选择矩阵中单元格的最大得分 3277. 查询子数组最大异或值 一、检查棋盘方格颜色是否相同 题目给定两个字符串来表示两个方格的坐标&#xff0c;让我们判断这两个方格的颜色是否相同&#xff0c;这…

C++——关联式容器(2):AVL树(平衡二叉树)

2.AVL树 2.1 AVL树的概念 在学习了二叉搜索树后&#xff0c;我们发现了二叉搜索树可以根据大小比较来进行类似于折半查找的操作&#xff0c;使得搜索时间复杂度达到logn的水准。但是在面对极端情况下&#xff0c;如近似有序的序列&#xff0c;那么整棵树的时间复杂度就有可能退…