掌握结构型模式——全景回顾

news2024/9/22 23:25:28

在前几篇文章中,我们详细探讨了多种结构型设计模式,今天来进行一个大总结——结构型设计模式主要关注类与对象的组合和组织,确保我们能够构建出稳固、灵活且易于维护的软件系统。无论你是初学者还是有经验的开发者,这篇文章都会帮你更好地掌握结构型模式的精髓。

结构型模式简介

结构型设计模式通过确定类与对象之间的关系,帮助我们形成更复杂且可维护的系统架构,它们通常涉及如何组合对象以实现更大的功能,并且可以分为七种主要模式:

  1. 适配器模式(Adapter Pattern)
  2. 桥接模式(Bridge Pattern)
  3. 组合模式(Composite Pattern)
  4. 装饰者模式(Decorator Pattern)
  5. 外观模式(Facade Pattern)
  6. 享元模式(Flyweight Pattern)
  7. 代理模式(Proxy Pattern)

一、适配器模式

核心思想

适配器模式通过将一个类的接口转换为另一个接口,使得原本由于接口不兼容而无法一起工作的类可以共同工作,适配器模式在兼容旧系统和第三方库时非常有用。

实现方式
Python实现
class OldInterface:
    def old_method(self):
        return "Old Interface"

class NewInterface:
    def new_method(self):
        return "New Interface"

class Adapter(NewInterface):
    def __init__(self, old_interface):
        self.old_interface = old_interface

    def new_method(self):
        return self.old_interface.old_method()
Java实现
public class OldInterface {
    public String oldMethod() {
        return "Old Interface";
    }
}

public interface NewInterface {
    String newMethod();
}

public class Adapter implements NewInterface {
    private OldInterface oldInterface;

    public Adapter(OldInterface oldInterface) {
        this.oldInterface = oldInterface;
    }

    @Override
    public String newMethod() {
        return oldInterface.oldMethod();
    }
}
应用场景
  • 当你需要兼容旧系统或第三方库时;
  • 当你需要将现有类与新接口兼容时。

二、桥接模式

核心思想

桥接模式通过分离抽象部分与实现部分,使得它们可以独立变化,桥接模式特别适用于需要跨越多个平台或支持多种实现方式的场景。

实现方式
Python实现
class DrawingAPI:
    def draw_circle(self, x, y, radius):
        pass

class OpenGLAPI(DrawingAPI):
    def draw_circle(self, x, y, radius):
        print(f"OpenGL Drawing: Circle at ({x}, {y}) with radius {radius}")

class Shape:
    def __init__(self, drawing_api):
        self.drawing_api = drawing_api

    def draw(self):
        pass

class Circle(Shape):
    def __init__(self, x, y, radius, drawing_api):
        super().__init__(drawing_api)
        self.x = x
        self.y = y
        self.radius = radius

    def draw(self):
        self.drawing_api.draw_circle(self.x, self.y, self.radius)
Java实现
public interface DrawingAPI {
    void drawCircle(double x, double y, double radius);
}

public class OpenGLAPI implements DrawingAPI {
    @Override
    public void drawCircle(double x, double y, double radius) {
        System.out.println("OpenGL Drawing: Circle at (" + x + ", " + y + ") with radius " + radius);
    }
}

public abstract class Shape {
    protected DrawingAPI drawingAPI;

    protected Shape(DrawingAPI drawingAPI) {
        this.drawingAPI = drawingAPI;
    }

    public abstract void draw();
}

public class Circle extends Shape {
    private double x, y, radius;

    public Circle(double x, double y, double radius, DrawingAPI drawingAPI) {
        super(drawingAPI);
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    @Override
    public void draw() {
        drawingAPI.drawCircle(x, y, radius);
    }
}
应用场景
  • 当你需要跨越多个平台或支持多种实现方式时;
  • 当你需要将抽象和实现解耦时。

三、组合模式

核心思想

组合模式允许你将对象组合成树形结构,以表示“部分-整体”的层次结构,使得客户端可以以一致的方式处理单个对象和组合对象。

实现方式
Python实现
class Graphic:
    def draw(self):
        pass

class Line(Graphic):
    def draw(self):
        print("Drawing a Line")

class Rectangle(Graphic):
    def draw(self):
        print("Drawing a Rectangle")

class CompositeGraphic(Graphic):
    def __init__(self):
        self.graphics = []

    def add(self, graphic):
        self.graphics.append(graphic)

    def draw(self):
        for graphic in self.graphics:
            graphic.draw()
Java实现
import java.util.ArrayList;
import java.util.List;

public abstract class Graphic {
    public abstract void draw();
}

public class Line extends Graphic {
    @Override
    public void draw() {
        System.out.println("Drawing a Line");
    }
}

public class Rectangle extends Graphic {
    @Override
    public void draw() {
        System.out.println("Drawing a Rectangle");
    }
}

public class CompositeGraphic extends Graphic {
    private List<Graphic> graphics = new ArrayList<>();

    public void add(Graphic graphic) {
        graphics.add(graphic);
    }

    @Override
    public void draw() {
        for (Graphic graphic : graphics) {
            graphic.draw();
        }
    }
}
应用场景
  • 当你需要表示对象的部分-整体层次结构时;
  • 当你希望客户端以统一的方式处理单个对象和组合对象时。

四、装饰者模式

核心思想

装饰者模式允许动态地为对象添加新功能,而不影响其他同类对象的功能。它通过将对象放入包含行为的装饰器对象中来实现功能扩展。

实现方式
Python实现
class Coffee:
    def cost(self):
        return 10

class MilkDecorator(Coffee):
    def __init__(self, coffee):
        self.coffee = coffee

    def cost(self):
        return self.coffee.cost() + 2
Java实现
public class Coffee {
    public int cost() {
        return 10;
    }
}

public class MilkDecorator extends Coffee {
    private Coffee coffee;

    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }

    @Override
    public int cost() {
        return coffee.cost() + 2;
    }
}
应用场景
  • 当你需要在不修改对象结构的情况下添加功能时;
  • 当你希望组合多个装饰者以实现更复杂的功能时。

五、外观模式

核心思想

外观模式为子系统中的一组接口提供了一个一致的界面,使得该子系统更容易使用。外观模式通过简化子系统接口,隐藏了复杂性。

实现方式
Python实现
class CPU:
    def freeze(self):
        print("CPU freeze")

    def jump(self, position):
        print(f"CPU jump to {position}")

    def execute(self):
        print("CPU execute")

class Memory:
    def load(self, position, data):
        print(f"Memory load data at {position}")

class HardDrive:
    def read(self, lba, size):
        return "data"

class ComputerFacade:
    def __init__(self):
        self.cpu = CPU()
        self.memory = Memory()
        self.hard_drive = HardDrive()

    def start(self):
        self.cpu.freeze()
        self.memory.load(0, self.hard_drive.read(100, 1024))
        self.cpu.jump(0)
        self.cpu.execute()
Java实现
public class CPU {
    public void freeze() {
        System.out.println("CPU freeze");
    }

    public void jump(long position) {
        System.out.println("CPU jump to " + position);
    }

    public void execute() {
        System.out.println("CPU execute");
    }
}

public class Memory {
    public void load(long position, String data) {
        System.out.println("Memory load data at " + position);
    }
}

public class HardDrive {
    public String read(long lba, int size) {
        return "data";
    }
}

public class ComputerFacade {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public ComputerFacade() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }

    public void start() {
        cpu.freeze();
        memory.load(0, hardDrive.read(100, 1024));
        cpu.jump(0);
        cpu.execute();
    }
}

应用场景

  • 当你希望简化复杂子系统的接口时;
  • 当你需要为多个子系统提供统一接口时。

六、享元模式

核心思想

享元模式通过共享尽可能多的相似对象来减少内存使用,它通常用于处理大量细粒度对象的场景,比如图形对象或字符对象。

实现方式
Python实现
class Flyweight:
    def __init__(self, intrinsic_state):
        self.intrinsic_state = intrinsic_state

    def operation(self, extrinsic_state):
        print(f"Intrinsic: {self.intrinsic_state}, Extrinsic: {extrinsic_state}")

class FlyweightFactory:
    _flyweights = {}

    @staticmethod
    def get_flyweight(key):
        if key not in FlyweightFactory._flyweights:
            FlyweightFactory._flyweights[key] = Flyweight(key)
        return FlyweightFactory._flyweights[key]
Java实现
import java.util.HashMap;
import java.util.Map;

public class Flyweight {
    private final String intrinsicState;

    public Flyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation(String extrinsicState) {
        System.out.println("Intrinsic: " + intrinsicState + ", Extrinsic: " + extrinsicState);
    }
}

public class FlyweightFactory {
    private static final Map<String, Flyweight> flyweights = new HashMap<>();

    public static Flyweight getFlyweight(String key) {
        if (!flyweights.containsKey(key)) {
            flyweights.put(key, new Flyweight(key));
        }
        return flyweights.get(key);
    }
}
应用场景
  • 当你需要处理大量相似对象时;
  • 当你希望通过共享来节省内存时。

七、代理模式

核心思想

代理模式为其他对象提供了一种代理以控制对这个对象的访问。代理模式可以用于延迟对象的创建、控制访问权限或添加额外的操作。

实现方式
Python实现
class RealSubject:
    def request(self):
        print("RealSubject: Handling request")

class Proxy:
    def __init__(self):
        self.real_subject = RealSubject()

    def request(self):
        print("Proxy: Before request")
        self.real_subject.request()
        print("Proxy: After request")
Java实现
public class RealSubject {
    public void request() {
        System.out.println("RealSubject: Handling request");
    }
}

public class Proxy {
    private RealSubject realSubject;

    public Proxy() {
        this.realSubject = new RealSubject();
    }

    public void request() {
        System.out.println("Proxy: Before request");
        realSubject.request();
        System.out.println("Proxy: After request");
    }
}
应用场景
  • 当你需要控制对象的访问时;
  • 当你需要延迟加载对象时。

总结

结构型设计模式为我们提供了组织代码、管理类与对象关系的强大工具,在实际开发中,灵活运用这些模式,可以大大提升代码的灵活性、可维护性和可扩展性。理解每个模式的核心思想和适用场景,能够帮助你在实际项目中选择最合适的设计模式。

希望通过这篇总结,大家能更清晰地了解结构型模式的精髓,并在实际开发中熟练运用。如果你有任何疑问或想法,欢迎在下方留言!别忘了关注我们的公众号,获取更多有趣的编程知识和实用的代码技巧,我们期待与你的交流与分享!
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2078700.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

计算循环冗余码(CRC)--软考笔记

1、什么是CRC循环冗余码&#xff08;CRC&#xff09; CRC&#xff08;Cyclic Redundancy Check&#xff09;是一种用于检测数据传输错误的校验码。它通过一个预定义的生成多项式来计算一个固定长度的校验值&#xff0c;这个值被附加到原始数据上一起发送。接收端使用相同的生成…

二叉树 - 完全二叉树的节点个数

222. 完全二叉树的节点个数 方法一&#xff1a;递归 /*** Definition for a binary tree node.* function TreeNode(val, left, right) {* this.val (valundefined ? 0 : val)* this.left (leftundefined ? null : left)* this.right (rightundefined ? nul…

多商户2.3.0后台顶部添加修改密码修复方法

问题&#xff1a;后台登录不能修改自己的密码&#xff1b; 解决方法&#xff1a; 修改前端代码&#xff0c;文件路径&#xff08;平台后台&#xff0c;商户后台一样的修改方法&#xff09;&#xff1a;src/layout/navBars/breadcrumb/user.vue 修改第一处 代码&#xff1a; 修…

IM即时通讯给娱乐社交、游戏等行业带来了什么影响?看这篇就知道

企业IM即时通讯技术的发展和应用&#xff0c;对我们的生活、工作、沟通和交流带来了显著的影响和改变。 IM即时通讯技术的发展不仅改变了我们的沟通方式&#xff0c;还提高了工作效率&#xff0c;促进了团队协作&#xff0c;保障了信息安全&#xff0c;并推动了业务创新。随着技…

机器人学导论之连杆参数

目录 一、连杆参数[1] 二、将下肢看作二连杆结构 三、参考文献 一、连杆参数[1] 1.1关节角 绕轴&#xff0c;从旋转到的角度。 备注&#xff1a;从z轴正方向看&#xff0c;顺时针为正&#xff0c;逆时针为负。 图 1 平面三连杆操作臂 以图1为例子&#xff0c; 表示…

文献解读-农业-第二十九期|《β-淀粉酶和磷脂酸参与板栗种子萌发》

关键词&#xff1a;农业&#xff1b;基因测序&#xff1b;变异检测&#xff1b; 文献简介 标题&#xff08;英文&#xff09;&#xff1a;Beta-amylase and phosphatidic acid involved in recalcitrant seed germination of Chinese chestnut标题&#xff08;中文&#xff09…

岩土工程中的渗流问题:有限单元法的理论与实践

有限单元法在岩土工程问题中应用非常广泛&#xff0c;很多商业软件如Plaxis/Abaqus/Comsol等都采用有限单元解法。尽管各类商业软件使用方便&#xff0c;但其使用对用户来说往往是一个“黑箱子”。相比而言&#xff0c;开源的有限元程序计算方法透明、计算过程可控&#xff0c;…

宝藏!盟主自控独家讲义:《掌中宝》(精卫篇)1-9章:甄选部分

本文内容&#xff0c;全部选自自动化考研联盟的&#xff1a;盟主自控独家讲义&#xff1a;《掌中宝》(精卫篇)。 Part1&#xff1a;资料封面&目录 Part2&#xff1a;资料各个章节具体内容 自控专属数学基础储备 第1章 自动控制的基本概念 第2章 控制系统的数学模型 第3章…

8.26算法训练

1.八皇后 Checker Challenge 输入&#xff1a; 6输出&#xff1a; 2 4 6 1 3 5 3 6 2 5 1 4 4 1 5 2 6 3 4是以前寒假写过的题目&#xff0c;所以有的影响&#xff0c;大致思路就是用深度遍历然后判断是否在对角线上就ok了&#xff0c;有大概思路的话&#xff0c; 还是不难的…

比特币的签名和验证(基于ECDSA)

比特币&#xff08;Bitcoin&#xff09;和以太坊&#xff08;Ethereum&#xff09;等区块链技术使用了加密算法来确保交易的安全性。私钥签名和公钥验证是这些算法的核心部分&#xff0c;主要用于证明交易的发起者拥有交易中使用的资金的控制权&#xff0c;而不需要暴露私钥本身…

【开源分享】java+swing+mysql简单学生信息管理系统设计与实现

个人主页&#xff1a;程序员杨工 个人简介&#xff1a;从事软件开发多年&#xff0c;前后端均有涉猎&#xff0c;具有丰富的开发经验 博客内容&#xff1a;全栈开发&#xff0c;分享Java、Python、Php、小程序、前后端、数据库经验和实战 文末有本人名片&#xff0c;希望和大家…

大模型学习全面教程:零基础入门至精通,一篇文章全掌握

人人都看得懂的大模型简介 大模型就像一座庞大的图书馆&#xff0c;里面有非常多的书籍。但与普通图书馆不同的是&#xff0c;这座图书馆中的每本书都是关于不同事物的描述和知识。而这些书籍中的每一页都代表了这个事物的一些特征或细节。现在&#xff0c;想象一下&#xff0…

蓝牙耳机哪个品牌最具有性价比?四大性价比拉满产品推荐!

蓝牙耳机哪个品牌最具有性价比&#xff1f;目前市面上的蓝牙耳机层出不重&#xff0c;蓝牙耳机的的品类也五花八门的&#xff0c;想要选择一款满意的蓝牙耳机也是需要花费一定的时间&#xff0c;大家购买时一定要格外注意&#xff0c;劣质耳机产品不仅使耳朵受到伤害&#xff0…

Python与Plotly实现多维度数据的动态可视化——交互式股票价格

目录 准备工作安装必要的库导入库 获取数据数据预处理创建交互式图表方法一&#xff1a;基本多线图方法二&#xff1a;带有滚动和区间选择的交互式图表方法三&#xff1a;可视化股票每日回报率的箱线图方法四&#xff1a;添加注释和标记的交互式图表 完整代码 在金融数据分析中…

ubuntu 小技巧 upower 查看电源模块之电池等功能

电脑使用时间久了&#xff0c;电池不耐用了&#xff0c;查看一下具体还剩多少容量&#xff0c;怎么看&#xff1f; ros2ros2-aspire4741:~$ upower -e /org/freedesktop/UPower/devices/battery_BAT0 /org/freedesktop/UPower/devices/line_power_ADP1 /org/freedesktop/UPowe…

C++ TinyWebServer项目总结(11. 定时器)

网络程序需要处理定时事件&#xff0c;如定期检测一个客户连接的活动状态。服务器程序通常管理着众多定时事件&#xff0c;有效地组织这些定时事件&#xff0c;使其在预期的时间被触发且不影响服务器的主要逻辑&#xff0c;对于服务器的性能有至关重要的影响。为此&#xff0c;…

“信”欣向荣,共“创”共赢 | 华宇TAS应用中间件认证工程师培训报名通道开启

信创&#xff0c;即“信息技术应用创新”。我国自主信息产业聚焦信息技术应用创新&#xff0c;旨在通过对IT硬件、软件等各个环节的重构&#xff0c;基于我国自有IT底层架构和标准&#xff0c;形成自有开放生态&#xff0c;从根本上解决本质安全问题&#xff0c;实现信息技术可…

牛客周赛 Round 57

A-小红喜欢1_牛客周赛 Round 57 (nowcoder.com) 思路&#xff1a; 简单记录一下 代码&#xff1a; #include<iostream> #include<algorithm> #include<cstring> #include<vector> #include<queue> #include<cmath> #define int long long…

CH340K的一个小bug

如果CH340和MCU在同一张PCB上&#xff0c;但是CH340用VUSB来供电&#xff0c;MCU用另外的3.3V电源单独供电。两块芯片只有TX&#xff0c;RX和GND直接相连接&#xff0c;DTR串联一个电容连接到MCU的Reset引脚。也就是说正常工作环境下不通过USB连接电脑&#xff0c;只有MUC工作&…

深度学习入门-08

基于小土堆学习 神经网络的搭建 神经网络pytorch官方文档&#xff1a; pytorch官方说明文档 torch.nn是pytorch存放神经网络的工具箱 Containers Containers&#xff08;容器&#xff09;在神经网络中通常不是一个特指的技术术语&#xff0c;但在编程和数据处理中&#xff0…