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

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

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. 总结

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

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

相关文章:

  • vscode 版本
  • Vscode无法加载文件,因为在此系统上禁止运行脚本
  • 大语言模型学习路径与开源模型推荐
  • 【第六节】C++设计模式(结构型模式)-Bridge(桥接)模式
  • SGLang中context-length参数的默认值来源解析
  • 【Python修仙编程】(二) Python3灵源初探(2)
  • 代码异常(js中forEach)NO.3
  • 基于无人机遥感的烟株提取和计数研究
  • EX_25/2/24
  • 【ISP】畸变校正 LDC
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_set_inherited_sockets
  • DeepSeek回答:AI时代Go语言学习路线
  • 神卓 S500 组网设备连接交换机的详细步骤
  • 从零开始玩转TensorFlow:小明的机器学习故事 6
  • 鸿蒙ArkTs如何实现pdf预览功能?
  • Spring 源码硬核解析系列专题(五):Spring Boot 自动装配的原理
  • MySQL 中表和视图的关系
  • React进阶之前端业务Hooks库(三)
  • 娛閑放鬆篇2
  • Jenkins 构建 Unity 打包 .apk 同时生成 .aab
  • 人民日报任平:从“地瓜经济”理论到民营经济促进法,读懂中国经济的成长壮大之道
  • 山西晋城一网红徒步野游线路据传发生驴友坠崖,当地已宣布封路
  • 深一度|上座率连创纪录撬动文旅,中超可否复制大连模式
  • CBA官方对孙铭徽罚款3万、广厦投资人楼明停赛2场罚款5万
  • 北京韩美林艺术馆党支部书记郭莹病逝,终年40岁
  • 新修订的《餐饮业促进和经营管理办法》公布,商务部解读