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

2024-09-08 08:20

本文主要是介绍设计模式大全和详解,含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 = Nonedef __new__(cls):if cls._instance is None:cls._instance = super(Singleton, cls).__new__(cls)return cls._instances1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # 输出: True
2. 工厂方法模式 (Factory Method)

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

class Animal:def speak(self):passclass 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):passdef create_vehicle(self):passclass 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 = Noneself.color = Noneclass CarBuilder:def __init__(self):self.car = Car()def set_model(self, model):self.car.model = modelreturn selfdef set_color(self, color):self.car.color = colorreturn selfdef build(self):return self.carbuilder = CarBuilder()
car = builder.set_model("Toyota").set_color("Red").build()
print(car.model, car.color)  # 输出: Toyota Red
5. 原型模式 (Prototype)

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

import copyclass Prototype:def __init__(self):self._objects = {}def register_object(self, name, obj):self._objects[name] = objdef 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 objclass 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_plugdef 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):passclass 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 = colorclass 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):passclass 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 5class MilkDecorator:def __init__(self, coffee):self.coffee = coffeedef cost(self):return self.coffee.cost() + 1coffee = Coffee()
print(coffee.cost())  # 输出: 5coffee_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_stateclass 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_subjectdef 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 = handlerreturn handlerdef handle(self, request):if hasattr(self, 'next_handler'):return self.next_handler.handle(request)return Noneclass 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):passclass 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 = lightdef execute(self):return self.light.turn_on()class LightOffCommand(Command):def __init__(self, light):self.light = lightdef 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):passclass TerminalExpression(Expression):def __init__(self, data):self.data = datadef interpret(self):return f"Interpreting {self.data}"class OrExpression(Expression):def __init__(self, expr1, expr2):self.expr1 = expr1self.expr2 = expr2def 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 = collectionself._index = 0def __next__(self):if self._index < len(self._collection):result = self._collection[self._index]self._index += 1return resultraise StopIterationclass 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):passclass ConcreteMediator(Mediator):def __init__(self, component1, component2):self.component1 = component1self.component2 = component2self.component1.mediator = selfself.component2.mediator = selfdef 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 = Nonedef do_a(self):print("Component 1 does A.")self.mediator.notify(self, "A")class Component2:def __init__(self):self.mediator = Nonedef 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 = stateclass Originator:def __init__(self):self.state = Nonedef create_memento(self):return Memento(self.state)def restore(self, memento):self.state = memento.stateoriginator = 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):passclass 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):passclass 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):passclass AddStrategy(Strategy):def execute(self, a, b):return a + bclass SubtractStrategy(Strategy):def execute(self, a, b):return a - bclass Context:def __init__(self, strategy):self.strategy = strategydef execute_strategy(self, a, b):return self.strategy.execute(a, b)context = Context(AddStrategy())
print(context.execute_strategy(5, 3))  # 输出: 8context.strategy = SubtractStrategy()
print(context.execute_strategy(5, 3))  # 输出: 2
10. 访问者模式 (Visitor)

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

class Visitor:def visit(self, element):passclass ConcreteVisitor(Visitor):def visit(self, element):return f"Visited {element.name}"class Element:def __init__(self, name):self.name = namedef 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 提供了灵活的语法,使得实现这些模式变得相对简单。选择合适的设计模式和场景能够提高代码的可维护性和可读性。

这篇关于设计模式大全和详解,含Python代码例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147600

相关文章

python中各种常见文件的读写操作与类型转换详细指南

《python中各种常见文件的读写操作与类型转换详细指南》这篇文章主要为大家详细介绍了python中各种常见文件(txt,xls,csv,sql,二进制文件)的读写操作与类型转换,感兴趣的小伙伴可以跟... 目录1.文件txt读写标准用法1.1写入文件1.2读取文件2. 二进制文件读取3. 大文件读取3.1

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

Python处理函数调用超时的四种方法

《Python处理函数调用超时的四种方法》在实际开发过程中,我们可能会遇到一些场景,需要对函数的执行时间进行限制,例如,当一个函数执行时间过长时,可能会导致程序卡顿、资源占用过高,因此,在某些情况下,... 目录前言func-timeout1. 安装 func-timeout2. 基本用法自定义进程subp

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

Python结合PyWebView库打造跨平台桌面应用

《Python结合PyWebView库打造跨平台桌面应用》随着Web技术的发展,将HTML/CSS/JavaScript与Python结合构建桌面应用成为可能,本文将系统讲解如何使用PyWebView... 目录一、技术原理与优势分析1.1 架构原理1.2 核心优势二、开发环境搭建2.1 安装依赖2.2 验

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm

使用Java将DOCX文档解析为Markdown文档的代码实现

《使用Java将DOCX文档解析为Markdown文档的代码实现》在现代文档处理中,Markdown(MD)因其简洁的语法和良好的可读性,逐渐成为开发者、技术写作者和内容创作者的首选格式,然而,许多文... 目录引言1. 工具和库介绍2. 安装依赖库3. 使用Apache POI解析DOCX文档4. 将解析

一文详解如何在Python中从字符串中提取部分内容

《一文详解如何在Python中从字符串中提取部分内容》:本文主要介绍如何在Python中从字符串中提取部分内容的相关资料,包括使用正则表达式、Pyparsing库、AST(抽象语法树)、字符串操作... 目录前言解决方案方法一:使用正则表达式方法二:使用 Pyparsing方法三:使用 AST方法四:使用字