适配器模式

类型:

类结构模式和对象结构模式
1、类结构模式采用继承的方式来组织接口和类(不推荐,因为Java单继承 能用接口就尽量用接口)

2、对象结构模式采用组合或聚合来组织对象

作用:

客户端通过适配器可以透明的调用目标接口

架构:

目标接口、适配者类、适配器类

代码:

在这里插入图片描述

对象适配器模式:

Adaptee

public class Adaptee {

    public void specific(){
        System.out.println("我是适配者");
    }

}

Adapter

public class Adapter implements Target {

    private Adaptee adaptee = new Adaptee();

    @Override
    public void show() {
        adaptee.specific();
    }
}

Target

public interface Target {

    void show();

}

Test

public class Test {

    public static void main(String[] args) {
        Target target = new Adapter();
        target.show();
    }

}

类适配器模式

Adaptee

public class Adaptee {

    public void specific(){
        System.out.println("我是适配者");
    }

}

Adapter

public class Adapter extends Adaptee implements Target{

    @Override
    public void show() {
        super.specific();
    }

}

Target

public interface Target {

    void show();

}

Test

public class Test {

    public static void main(String[] args) {
        Target target = new Adapter();
        target.show();
    }

}

总结:

对象适配器模式:就是在Adapter中创建Adaptee的对象,通过Adaptee对象调用它的方法

类适配器模式:Adapter继承Adaptee实现Target重写Target的show方法,show方法体中调用Adaptee的special方法,多态创建Target对象 调用Adapter的show方法。

用生活中的例子来理解适配器模式:例如投影仪和笔记本连接,笔记本没有HDMI接口需要用HDMI转USB或者vga的适配器转换才可以连上

个人理解:说白了就是通过A调用B里面的方法。

类适配器和对象适配器的区别
代码层面:类适配器中继承Adaptee类用super调用Adaptee的方法;对象适配器创建Adaptee对象通过Adaptee对象调用Adaptee方法。
作用层面:Adaptee想要调用Target接口但是无法直接调用情况下,通过适配器类Adapter(继承Adaptee实现Target)可以隐式的进行调用

posted @   有锦  阅读(1)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示