适配器模式

适配器模式

       适配器模式的使用场景:我们在应用程序中已经设计好了功能接口,但是与第三方提供的接口类不一致。第三方的接口类已经不能更改,我们设计的功能接口也是符合需求也不能改,为了使得这些接口不兼容的类(即不能在一起工作)可以一起工作,就可以使用适配器模式。

       Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. -- GoF

       适配器模式有两种类型:类适配器模式对象适配器模式

       适配器模式参与者:

Client:与Target协同交互的类;

TargetClient所使用的相关接口或(抽象)类

Adaptee: 需要适配的类

Adapter:   适配器类,负责Adaptee中的接口方法与Target中的接口方法进行适配   

1、类适配器模式:

代码如下:

//Target,此处为接口
public interface Target {

    void request();
}

//Adaptee类
public class Adaptee {

    public void specificRequest() {
        System.out.println("adaptee 处理请求");
    }
}

//Adapter类
public class Adapter extends Adaptee implements Target{
    @Override
    public void request() {
        this.specificRequest();
    }
}


//测试类
public class Test {
    public static void main(String[] args) {
        Target target = new Adapter();
        target.request();
    }
}

类适配器模式是通过类的继承实现的,缺点Adapter和Adaptee是耦合度高,而且一些高级语言像Java、C#不支持多继承,如果Target为(抽象)类,则只能使用对象适配器模式。

2、对象适配器模式

对象适配器模式是通过Adapter类聚合持有Adaptee类对象adaptee实现的,代码如下:

//Target,此处为接口
public interface Target {

    void request();
}

//Adaptee类
public class Adaptee {

    public void specificRequest() {
        System.out.println("adaptee 处理请求");
    }
}

//Adapter类
public class Adapter extends Adaptee implements Target{
    private Adaptee adaptee;

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

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


//测试类
public class Test {
    public static void main(String[] args) {
        Target target = new Adapter(new Adaptee());
        target.request();
    }
}

小结:

        适配器模式通常在软件开发后期或者维护期使用。在设计阶段如果出现接口方法不匹配,应该统一接口方法,而不是使用适配器模式。适配器模式更常见地用于我们适配第三方开发组件类提供的接口上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值