设计模式之适配器模式

本文介绍了适配器模式的基本概念及其实现方式,包括类适配器和对象适配器两种类型,并通过Java代码示例展示了如何将一个类的接口转换成另一个接口,使原本因接口不兼容而无法合作的类能够协同工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

适配器模式(Adapter):将一个类的接口转换成客户端(client)希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
Convert the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

适配器
这个有类adaptee方法method1()和method2()继承自ownInterface接口,现在有一个接口target有三个方法,需要用到method1()或者method2(),为了不造成耦合,需要一个适配器adapter将adaptee进行适配(java中有直接继承adaptee和 委托 方法),这样client就可以通过target调用adaptee的方法或者是自己实现的another

适配器模式分为类适配器和对象适配器.
类适配器的实现就是通过继承adaaptee实现适配,对象适配器就是用委托的方式实现适配

原始类

// 原始类
public class Adaptee implements OwnInterface {
    public void method1() {
        System.out.println("原有功能1");
    }
    public void method2() {
        System.out.println("原有功能2");
    }
}
// 目标接口,或称为标准接口
public interface Target {
    public void method1();
    public void method2();
    public void method3();
}

// 自己的实现
public class Another implements Target {
    public void method1() {
        System.out.println("自己实现的功能1");
    }
    public void method2() {
        System.out.println("自己实现的功能2");
    }
    public void method3() {
        System.out.println("自己实现的功能3");
    }
}

类适配器

public class Adapter extends Adaptee implements Target{
    public void method1() {
        super.method1();
    }

    public void method2() {
        super.method2();
    }
    public void method3() {
        System.out.println("自己实现的功能1");
    }
}

对象适配器

public class Adapter implements Target{
    //委托或者代理
    private Adaptee adaptee = new Adaptee();

    public void method1() {

        this.adaptee.method1();
    }

    public void method2() {

        this.adaptee.method2();
    }

    public void method3() {
        System.out.println("自己实现的功能1");

    }
}

client类

public class Client {
    public static void main(String[] args) {
        // 使用普通功能类
        Target another= new Another();
        another.method1();

        // 使用特殊功能类,即适配类,
        // 需要先创建一个被适配类的对象作为参数
        Target adapter = new Adapter();
        adapter.method1();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值