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

设计模式|结构型模式总结

1. 介绍

结构型设计模式(Structural Patterns) 主要关注类与对象的组合,以提高代码的灵活性和可维护性。这些模式帮助创建更大结构,同时保持代码的低耦合性。

结构型设计模式包括以下七种:

  1. 适配器模式(Adapter)

  2. 桥接模式(Bridge)

  3. 组合模式(Composite)

  4. 装饰器模式(Decorator)

  5. 外观模式(Facade)

  6. 享元模式(Flyweight)

  7. 代理模式(Proxy)


2. 适配器模式(Adapter)

目的:使接口不兼容的类能够协同工作。

实现方式:通过包装(Wrapper)转换接口。

示例(Python 实现):

class OldSystem:
    def specific_request(self):
        return "Old System Data"

class Adapter:
    def __init__(self, old_system):
        self.old_system = old_system
    
    def request(self):
        return self.old_system.specific_request()

old_system = OldSystem()
adapter = Adapter(old_system)
print(adapter.request())

3. 桥接模式(Bridge)

目的:分离抽象部分和实现部分,使它们可以独立变化。

示例

class Implementation:
    def operation(self):
        pass

class ConcreteImplementationA(Implementation):
    def operation(self):
        return "Implementation A"

class Abstraction:
    def __init__(self, implementation):
        self.implementation = implementation
    
    def operation(self):
        return self.implementation.operation()

abstraction = Abstraction(ConcreteImplementationA())
print(abstraction.operation())

4. 组合模式(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):
        return "+".join([child.operation() for child in self.children])

leaf = Leaf()
composite = Composite()
composite.add(leaf)
print(composite.operation())

5. 装饰器模式(Decorator)

目的:动态地给对象增加额外的功能。

示例

def decorator(func):
    def wrapper():
        print("Before Function Call")
        func()
        print("After Function Call")
    return wrapper

@decorator
def function():
    print("Hello")

function()

6. 外观模式(Facade)

目的:提供一个统一的接口,简化子系统的复杂性。

示例

class SubsystemA:
    def operation(self):
        return "SubsystemA Operation"

class SubsystemB:
    def operation(self):
        return "SubsystemB Operation"

class Facade:
    def __init__(self):
        self.a = SubsystemA()
        self.b = SubsystemB()
    
    def operation(self):
        return f"{self.a.operation()} + {self.b.operation()}"

facade = Facade()
print(facade.operation())

7. 享元模式(Flyweight)

目的:减少内存占用,通过共享相似对象来避免创建大量相同对象。

示例

class Flyweight:
    _instances = {}
    
    @staticmethod
    def get_instance(key):
        if key not in Flyweight._instances:
            Flyweight._instances[key] = Flyweight()
        return Flyweight._instances[key]

fw1 = Flyweight.get_instance("A")
fw2 = Flyweight.get_instance("A")
print(fw1 is fw2)  # True

8. 代理模式(Proxy)

目的:控制对象的访问,如权限控制、远程代理、虚拟代理。

示例

class RealSubject:
    def request(self):
        return "RealSubject Request"

class Proxy:
    def __init__(self, real_subject):
        self.real_subject = real_subject
    
    def request(self):
        print("Proxy: Checking Access")
        return self.real_subject.request()

real = RealSubject()
proxy = Proxy(real)
print(proxy.request())

9. 总结

结构型设计模式 通过合理组织类和对象,使系统更灵活、可扩展。根据不同需求,选择合适的模式:

模式主要作用
适配器模式连接不同接口的类
桥接模式分离抽象和实现,提高扩展性
组合模式处理树形结构,使单个对象和组合对象一致
装饰器模式动态添加功能,提高灵活性
外观模式提供统一接口,简化复杂系统调用
享元模式共享对象,减少内存占用
代理模式控制对象访问,如远程代理、权限管理

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

相关文章:

  • Linux 命令大全完整版(09)
  • 华为昇腾910b服务器部署DeepSeek翻车现场
  • RFID:汽车智能化产线工艺加工的指挥棒
  • 在Ubuntu系统上部署Dify(开源大语言模型应用开发平台)
  • 前端px转为rem的自适应解决方案
  • [VMware]卸载VMware虚拟机和Linux系统ubuntu(自记录版)
  • 论文解读<CRAW4LLM: Efficient Web Crawling for LLM Pretraining>
  • 记一次pytorch训练loss异常的问题
  • 驱动开发系列39 - Linux Graphics 3D 绘制流程(二)- 设置渲染管线
  • 系统架构设计:软件测试需要掌握的常用方法
  • MySQL的锁机制和锁算法
  • 卷积这个词在卷积神经网络中应该怎么理解
  • Unity XR-XR Interaction Toolkit开发使用方法(十一)组件介绍(XR Interactable)
  • Redis|复制 REPLICA
  • python的列表和元组别再傻傻分不清啦
  • C# WinForm 中的事件驱动模型
  • Java 算法和数据结构 答案整理,最新面试题
  • 计算机毕业设计SpringBoot+Vue.js大创管理系统(源码+文档+PPT+讲解)
  • 大模型面试问题准备
  • 力扣(leetcode)每日一题 1472 设计浏览器历史记录 - 数组