深入解析常见的设计模式

news/2024/11/27 0:30:01/

在本篇博文中,我们将逐个深入解析常见的设计模式,包括它们的目的、结构和具体示例,帮助你更好地理解和应用这些模式。

一、创建型模式

1. 单例模式(Singleton)

目的:确保一个类只有一个实例,并提供全局访问。

示例

class Singleton:  _instance = None  def __new__(cls):  if cls._instance is None:  cls._instance = super(Singleton, cls).__new__(cls)  return cls._instance  singleton1 = Singleton()  
singleton2 = Singleton()  print(singleton1 is singleton2)  # Output: True

2. 工厂方法模式(Factory Method)

目的:定义一个创建对象的接口,使子类决定实例化哪一个类。

示例

class Product:  def operation(self):  pass  class ConcreteProductA(Product):  def operation(self):  return "Result of ConcreteProductA"  class ConcreteProductB(Product):  def operation(self):  return "Result of ConcreteProductB"  class Creator:  def factory_method(self):  raise NotImplementedError  class ConcreteCreatorA(Creator):  def factory_method(self):  return ConcreteProductA()  class ConcreteCreatorB(Creator):  def factory_method(self):  return ConcreteProductB()  creator = ConcreteCreatorA()  
product = creator.factory_method()  
print(product.operation())  # Output: Result of ConcreteProductA

3. 抽象工厂模式(Abstract Factory)

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

示例

class AbstractFactory:  def create_product_a(self):  pass  def create_product_b(self):  pass  class ConcreteFactory1(AbstractFactory):  def create_product_a(self):  return "Product A1"  def create_product_b(self):  return "Product B1"  class ConcreteFactory2(AbstractFactory):  def create_product_a(self):  return "Product A2"  def create_product_b(self):  return "Product B2"  factory = ConcreteFactory1()  
print(factory.create_product_a())  # Output: Product A1

4. 建造者模式(Builder)

目的:将复杂对象的构建与表示分离,使同样的构建过程可以创建不同的表示。

示例

class Product:  def __init__(self):  self.parts = []  def add(self, part):  self.parts.append(part)  class Builder:  def __init__(self):  self.product = Product()  def build_part1(self):  self.product.add("Part1")  def build_part2(self):  self.product.add("Part2")  def get_product(self):  return self.product  builder = Builder()  
builder.build_part1()  
builder.build_part2()  
product = builder.get_product()  
print(product.parts)  # Output: ['Part1', 'Part2']

5. 原型模式(Prototype)

目的:通过复制现有实例来创建新实例,而不是使用构造函数。

示例

import copy  class Prototype:  def clone(self):  return copy.deepcopy(self)  class ConcretePrototype(Prototype):  def __init__(self, value):  self.value = value  prototype = ConcretePrototype("Original")  
clone = prototype.clone()  
clone.value = "Clone"  
print(prototype.value)  # Output: Original  
print(clone.value)       # Output: Clone

二、结构型模式

1. 适配器模式(Adapter)

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

示例

class Target:  def request(self):  return "Target: Default behavior"  class Adaptee:  def specific_request(self):  return "Adaptee: Specific behavior"  class Adapter(Target):  def __init__(self, adaptee):  self.adaptee = adaptee  def request(self):  return self.adaptee.specific_request()  adaptee = Adaptee()  
adapter = Adapter(adaptee)  
print(adapter.request())  # Output: Adaptee: Specific behavior

2. 桥接模式(Bridge)

目的:将抽象部分与其实现部分分离,以便可以独立变换。

示例

class Abstraction:  def __init__(self, implementor):  self.implementor = implementor  def operation(self):  return f"Abstraction: {self.implementor.operation_impl()}"  class Implementor:  def operation_impl(self):  return "Implementor"  class ConcreteImplementorA(Implementor):  def operation_impl(self):  return "ConcreteImplementorA"  implementor = ConcreteImplementorA()  
abstraction = Abstraction(implementor)  
print(abstraction.operation())  # Output: Abstraction: ConcreteImplementorA

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 f"Composite: [{', '.join(results)}]"  composite = Composite()  
composite.add(Leaf())  
composite.add(Leaf())  
print(composite.operation())  # Output: Composite: [Leaf, Leaf]

4. 装饰模式(Decorator)

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

示例

class Component:  def operation(self):  return "Basic Component"  class Decorator(Component):  def __init__(self, component):  self.component = component  def operation(self):  return f"Decorator: {self.component.operation()}"  decorated_component = Decorator(Component())  
print(decorated_component.operation())  # Output: Decorator: Basic Component

5. 外观模式(Facade)

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

示例

class Subsystem1:  def operation1(self):  return "Subsystem1: Ready"  class Subsystem2:  def operation2(self):  return "Subsystem2: Ready"  class Facade:  def __init__(self):  self.subsystem1 = Subsystem1()  self.subsystem2 = Subsystem2()  def operation(self):  return f"{self.subsystem1.operation1()} and {self.subsystem2.operation2()}"  facade = Facade()  
print(facade.operation())  # Output: Subsystem1: Ready and Subsystem2: Ready

6. 享元模式(Flyweight)

目的:通过共享技术来尽量减少内存使用。

示例

class Flyweight:  def __init__(self, intrinsic_state):  self.intrinsic_state = intrinsic_state  def operation(self, extrinsic_state):  return f"Intrinsic: {self.intrinsic_state}, Extrinsic: {extrinsic_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("X")  
flyweight2 = factory.get_flyweight("Y")  
print(flyweight1.operation("A"))  # Output: Intrinsic: X, Extrinsic: A

7. 代理模式(Proxy)

目的:通过一个代理对象来控制对另一个对象的访问。

示例

class RealSubject:  def request(self):  return "RealSubject: Handling request"  class Proxy:  def __init__(self):  self.real_subject = RealSubject()  def request(self):  return f"Proxy: Forwarding request to {self.real_subject.request()}"  proxy = Proxy()  
print(proxy.request())  # Output: Proxy: Forwarding request to RealSubject: Handling request

三、行为型模式

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

目的:将请求的发送者与接收者解耦。

示例

class Handler:  def set_next(self, handler):  self.next_handler = handler  return handler  def handle(self, request):  if self.next_handler:  return self.next_handler.handle(request)  return None  class ConcreteHandlerA(Handler):  def handle(self, request):  if request == "A":  return "Handler A handled the request"  return super().handle(request)  class ConcreteHandlerB(Handler):  def handle(self, request):  if request == "B":  return "Handler B handled the request"  return super().handle(request)  handler_a = ConcreteHandlerA()  
handler_b = ConcreteHandlerB()  
handler_a.set_next(handler_b)  print(handler_a.handle("A"))  # Output: Handler A handled the request  
print(handler_a.handle("B"))  # Output: Handler B handled the request

2. 命令模式(Command)

目的:将请求封装为一个对象,以便于参数化客户代码。

示例

class Command:  def execute(self):  pass  class ConcreteCommand(Command):  def __init__(self, receiver):  self.receiver = receiver  def execute(self):  self.receiver.action()  class Receiver:  def action(self):  return "Receiver: Action executed"  receiver = Receiver()  
command = ConcreteCommand(receiver)  
command.execute()  # Output: Receiver: Action executed

3. 解释器模式(Interpreter)

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

示例

class Expression:  def interpret(self, context):  pass  class TerminalExpression(Expression):  def interpret(self, context):  return context.split().count("Hello")  context = "Hello world! Hello everyone!"  
terminal = TerminalExpression()  
print(terminal.interpret(context))  # Output: 2

4. 迭代器模式(Iterator)

目的:提供一种顺序访问聚合对象元素的方法,而无需暴露其内部表示。

示例

class Iterator:  def __init__(self, collection):  self.collection = collection  self.index = 0  def next(self):  item = self.collection[self.index]  self.index += 1  return item  def has_next(self):  return self.index < len(self.collection)  collection = ["A", "B", "C"]  
iterator = Iterator(collection)  
while iterator.has_next():  print(iterator.next())  # Output: A, B, C

5. 中介者模式(Mediator)

目的:通过一个中介对象来减少对象之间的通信复杂度。

示例

class Mediator:  def notify(self, sender, event):  pass  class ConcreteMediator(Mediator):  def __init__(self, component1, component2):  self.component1 = component1  self.component2 = component2  def notify(self, sender, event):  if sender == self.component1 and event == "A":  self.component2.do_b()  class Component1:  def __init__(self, mediator):  self.mediator = mediator  def do_a(self):  print("Component1: Doing A")  self.mediator.notify(self, "A")  class Component2:  def __init__(self, mediator):  self.mediator = mediator  def do_b(self):  print("Component2: Doing B")  mediator = ConcreteMediator(Component1(mediator), Component2(mediator))  
mediator.component1.do_a()  
# Output:  
# Component1: Doing A  
# Component2: Doing B

6. 备忘录模式(Memento)

目的:在不暴露对象实现细节的情况下,捕获对象的内部状态。

示例

class Memento:  def __init__(self, state):  self.state = state  class Originator:  def __init__(self):  self.state = None  def set_state(self, state):  self.state = state  def save(self):  return Memento(self.state)  def restore(self, memento):  self.state = memento.state  originator = Originator()  
originator.set_state("State1")  
memento = originator.save()  
originator.set_state("State2")  
originator.restore(memento)  
print(originator.state)  # Output: State1

7. 观察者模式(Observer)

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

示例

class Observer:  def update(self, message):  pass  class ConcreteObserver(Observer):  def update(self, message):  print(f"Observer received: {message}")  class Subject:  def __init__(self):  self.observers = []  def subscribe(self, observer):  self.observers.append(observer)  def unsubscribe(self, observer):  self.observers.remove(observer)  def notify(self, message):  for observer in self.observers:  observer.update(message)  # 创建观察者和主题  
observer1 = ConcreteObserver()  
observer2 = ConcreteObserver()  
subject = Subject()  # 订阅观察者  
subject.subscribe(observer1)  
subject.subscribe(observer2)  # 通知所有观察者  
subject.notify("Hello Observers!")  
# Output:  
# Observer received: Hello Observers!  
# Observer received: 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 set_state(self, state):  self.state = state  def request(self):  return self.state.handle()  context = Context()  
print(context.request())  # Output: State A: Handling  context.set_state(ConcreteStateB())  
print(context.request())  # Output: State B: Handling

9. 策略模式(Strategy)

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

示例

class Strategy:  def execute(self):  pass  class ConcreteStrategyA(Strategy):  def execute(self):  return "Strategy A executed!"  class ConcreteStrategyB(Strategy):  def execute(self):  return "Strategy B executed!"  class Context:  def __init__(self, strategy):  self.strategy = strategy  def set_strategy(self, strategy):  self.strategy = strategy  def execute_strategy(self):  return self.strategy.execute()  context = Context(ConcreteStrategyA())  
print(context.execute_strategy())  # Output: Strategy A executed!  context.set_strategy(ConcreteStrategyB())  
print(context.execute_strategy())  # Output: Strategy B executed!

10. 模板方法模式(Template Method)

目的:定义一个算法的框架,而将一些步骤延迟到子类中。

示例

class AbstractClass:  def template_method(self):  self.step1()  self.step2()  def step1(self):  pass  def step2(self):  pass  class ConcreteClass(AbstractClass):  def step1(self):  return "Step 1 completed."  def step2(self):  return "Step 2 completed."  concrete = ConcreteClass()  
concrete.template_method()  
# Output: Step 1 completed. Step 2 completed.

11. 访问者模式(Visitor)

目的:将操作封装到一个访问者对象中,以便于在不改变目标对象类的情况下增加新的操作。

示例

class Element:  def accept(self, visitor):  pass  class ConcreteElementA(Element):  def accept(self, visitor):  visitor.visit(self)  class ConcreteElementB(Element):  def accept(self, visitor):  visitor.visit(self)  class Visitor:  def visit(self, element):  pass  class ConcreteVisitor(Visitor):  def visit(self, element):  return f"Visited {type(element).__name__}"  elements = [ConcreteElementA(), ConcreteElementB()]  
visitor = ConcreteVisitor()  for element in elements:  print(element.accept(visitor))  # Output: Visited ConcreteElementA  Visited ConcreteElementB

以上是对观察者模式及其他行为型设计模式的详细介绍和示例。如果你还有其他问题或者想深入了解的内容,随时告诉我!


 


http://www.ppmy.cn/news/1550188.html

相关文章

前端数据可视化思路及实现案例

目录 一、前端数据可视化思路 &#xff08;一&#xff09;明确数据与目标 &#xff08;二&#xff09;选择合适的可视化图表类型 &#xff08;三&#xff09;数据与图表的绑定及交互设计 &#xff08;四&#xff09;页面布局与样式设计 二、具体案例&#xff1a;使用 Ech…

SQL99版链接查询语法

连接查询按照功能分类 内连接 等值连接 非等值连接 自连接 //92SQL 外连接&#xff1a; //红色的连接查询类型92版SQL 左外连接 右外连接 全外连接 交叉连接 #剩下连接类型的SQL语法就不是前面同一个发布版本了 99版SQL语法格式区别于92版的是连接不在是用“”了&am…

Linux字符串中的大写字母转换为小写字母

echo $1 | tr A-Z a-z 是一个 Unix/Linux 命令组合&#xff0c;作用是将输入的字符串中的大写字母转换为小写字母。 详细解释&#xff1a; 1. echo $1&#xff1a; echo 命令用于输出其后的内容。$1 是一个变量&#xff0c;表示传给脚本或命令的第一个参数。如果你在命令行中执…

Ajax学习笔记,第一节:语法基础

Ajax学习笔记&#xff0c;第一节&#xff1a;语法基础 一、概念 1、什么是Ajax 使用浏览器的 XMLHttpRequest 对象 与服务器通信2、什么是axios Axios是一个基于Promise的JavaScript库&#xff0c;支持在浏览器和Node.js环境中使用。相较于Ajax&#xff0c;Axios提供了更多…

现代密码学

概论 计算机安全的最核心三个关键目标&#xff08;指标&#xff09;/为&#xff1a;保密性 Confidentiality、完整性 Integrity、可用性 Availability &#xff0c;三者称为 CIA三元组 数据保密性&#xff1a;确保隐私或是秘密信息不向非授权者泄漏&#xff0c;也不被非授权者使…

嵌入式的C/C++:深入理解 static、const 与 volatile 的用法与特点

目录 一、static 1、static 修饰局部变量 2、 static 修饰全局变量 3、static 修饰函数 4、static 修饰类成员 5、小结 二、const 1、const 修饰普通变量 2、const 修饰指针 3、const 修饰函数参数 4. const 修饰函数返回值 5. const 修饰类成员 6. const 与 #defi…

windows下安装wsl的ubuntu,同时配置深度学习环境

写在前面&#xff0c;本次文章只是个人学习记录&#xff0c;不具备教程的作用。个别信息是网上的&#xff0c;我会标注&#xff0c;个人是gpt生成的 安装wsl 直接看这个就行&#xff1b;可以不用备份软件源。 https://blog.csdn.net/weixin_44301630/article/details/1223900…

十七:Web内容协商与资源表述

在现代Web架构中,随着用户设备、语言和网络环境的多样化,如何高效地传递和获取适合的内容变得尤为重要。Web内容协商(Content Negotiation)和资源表述(Representation of Resources)是解决这一问题的重要技术手段。它们帮助服务器根据客户端的需求动态提供最合适的资源,…