设计模式大全和详解,含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

相关文章

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

MyBatis常用XML语法详解

《MyBatis常用XML语法详解》文章介绍了MyBatis常用XML语法,包括结果映射、查询语句、插入语句、更新语句、删除语句、动态SQL标签以及ehcache.xml文件的使用,感兴趣的朋友跟随小... 目录1、定义结果映射2、查询语句3、插入语句4、更新语句5、删除语句6、动态 SQL 标签7、ehc

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

从基础到高级详解Go语言中错误处理的实践指南

《从基础到高级详解Go语言中错误处理的实践指南》Go语言采用了一种独特而明确的错误处理哲学,与其他主流编程语言形成鲜明对比,本文将为大家详细介绍Go语言中错误处理详细方法,希望对大家有所帮助... 目录1 Go 错误处理哲学与核心机制1.1 错误接口设计1.2 错误与异常的区别2 错误创建与检查2.1 基础

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符