浅谈设计模式——适配器模式(Adapter)

适配器模式(Adapter Pattern)?

结构型模式

适配器模式(或包装模式)是将一个类的接口变换成客户期待的另一种接口,从而使原本因接口不匹配而不能在一起工作的两个类能够在一起工作。

Convert the interface of a class into another interface client expect. Adapter lets class work together that could not otherwise because of incompatible interfaces.

就是 转换器。

UML

Adpater

  • Client: 调用目标类或程序。
  • Target: 客户想用的接口。
  • Adapter:按照要求对适配对象接口实现接口形式的适配转换。
  • Adaptee:需要进行适配的类或对象。
  • request:客户端想执行的操作。
  • specificRequest:适配对象中能完成request方法功能 的实现。

代码实例

public class AdapterTest {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("d:/AdaptText.txt");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
        System.out.println(bufferedReader.readLine());

    }
}

是不是感觉很熟?其实InputStreamReader就是一个Adapter,将Stream字节流转换成字符流

适配器实现

  • Adaptee
public class Adaptee {
    public void specificRequest(){
        //specific方法
        
    }
}
  • Target
public interface Target {
    public void request();
}
  • 适配器Adapter
public class Adapter extends Adaptee implements Target{
    @Override
    public void request() {
        super.specificRequest();
        //进行业务处理
    }
}
  • Cilent用户端
public class Client {
    public static void main(String[] args) {
        Target target = new Adapter();
        target.request();
    }

}

总结

对开发维护来讲,该模式增加了一层代码抽象,但如果在不允许重写现有代码的情况下,适配器就该上场了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值