设计模式之【适配器模式】

类适配器实现(继承)

类适配器通过继承来实现适配器功能

java 复制代码
// 目标接口
public interface Target {
    void request();
}

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

// 适配器
public class Adapter extends Adaptee implements Target {
    /**
     * 采用继承的方式实现转换功能
     */
    @Override
    public void request() {
        super.specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}

对象适配器实现(组合)

对象适配器通过组合来实现适配器功能

java 复制代码
// 目标接口
public interface Target {
    void request();
}

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

// 适配器
public class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}
相关推荐
宋情写4 分钟前
java-IDEA
java·ide·intellij-idea
最贪吃的虎13 分钟前
Git: rebase vs merge
java·运维·git·后端·mysql
资生算法程序员_畅想家_剑魔32 分钟前
Java常见技术分享-12-多线程安全-锁机制
java·开发语言
会飞的架狗师35 分钟前
DDD笔记 | 实体、值对象、聚合、聚合根
设计模式·设计规范
一叶飘零_sweeeet40 分钟前
吃透 Spring 体系结构
java·spring
2401_837088501 小时前
简要总结 HashSet 和 HashMap(Java)
java·开发语言
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于Java的家政服务管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
小白学大数据1 小时前
Java 爬虫对百科词条分类信息的抓取与处理
java·开发语言·爬虫
Coder_Boy_2 小时前
Spring 核心思想与企业级最佳特性(实践级)事务相关
java·数据库·spring
历程里程碑2 小时前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法