博客
关于我
设计模式之适配器模式
阅读量:706 次
发布时间:2019-03-21

本文共 1656 字,大约阅读时间需要 5 分钟。

Adapter 模式:接口适配器实现模式优化

Adapter 模式(接口适配器模式)是一种软件设计模式,用于解决现有类与新系统或新环境不兼容的问题。这种模式通过创建一个间接将两个不兼容的接口连接起来,从而达成双方的平衡。

Adapter 模式的核心思想是当系统中有类的接口与其他代码不兼容时,通过使用适配器类解决不兼容问题,使得原本无法一起工作的类能够协同工作。这种方法不仅提升了系统的灵活性,还增强了系统的可维护性和可扩展性。

Adapter 模式主要应用于以下场景:

  • 当需要将某些现有的类与其他系统或环境集成时,尤其是当这些类的接口与目标系统的需求不匹配时,Adapter 模式是一个非常有效的解决方案。通过在源系统和目标系统之间设计一个适配器,实现两者的互操作性。

  • 在类的继承关系中,当某些子类缺少一些公共功能或接口时,Adapter 模式可以用来补充这些缺少的功能,使其能够与超类或其他部分的系统无缝对接。

  • Adapter 模式的关键优点包括:

  • 符合单一职责原则:适配器类专注于将源接口转换为目标接口,避免混淆和误用。

  • 符合开闭原则:系统可以自开放,而不必Modified为不支持修改的代码架构,也能支持已有的不兼容的系统接口。

  • 以下是Adapter 模式的实现示例:

    对象适配器示例:

    package com.fen.dou.sjms.adapter;public class ObjectAdapterTest {    public static void main(String[] args) {        Adaptee adaptee = new Adaptee();        Target target = new Adapter(adaptee);        target.output5v();    }}interface Target {    int output5v();}class Adapter implements Target {    private Adaptee adaptee;    public Adapter(Adaptee adaptee) {        this.adaptee = adaptee;    }    @Override    public int output5v() {        int i = adaptee.output220v();         return 5;    }}class Adaptee {    public int output220v() {        return 220;    }}

    类适配器示例:

    package com.fen.dou.sjms.adapter;public class ClassAdapterTest {    public static void main(String[] args) {        Adapter adpater = new Adapter();        adpater.output5v();    }}class Adapter extends Adaptee implements Target {    @Override    public int output5v() {        int i = output220v();        return 5;    }}interface Target {    int output5v();}class Adaptee {    public int output220v() {        return 220;    }}

    通过以上示例可以看出,Adapter 模式允许原本接口不兼容的类或系统通过适配器实现信息透 bridge,实现两者的协同工作。无论是对象适配器还是类适配器,都能够满足适配需求,确保系统的稳定性和兼容性。

    转载地址:http://cggez.baihongyu.com/

    你可能感兴趣的文章
    no1
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    node exporter完整版
    查看>>
    node HelloWorld入门篇
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node JS: < 二> Node JS例子解析
    查看>>
    Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
    查看>>
    Node 裁切图片的方法
    查看>>
    Node+Express连接mysql实现增删改查
    查看>>
    node, nvm, npm,pnpm,以前简单的前端环境为什么越来越复杂
    查看>>
    Node-RED中Button按钮组件和TextInput文字输入组件的使用
    查看>>
    vue3+Ts 项目打包时报错 ‘reactive‘is declared but its value is never read.及解决方法
    查看>>
    Node-RED中Switch开关和Dropdown选择组件的使用
    查看>>
    Node-RED中使用html节点爬取HTML网页资料之爬取Node-RED的最新版本
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>
    Node-RED中使用json节点解析JSON数据
    查看>>
    Node-RED中使用node-random节点来实现随机数在折线图中显示
    查看>>
    Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
    查看>>