技术程序员Java学习笔记

设计模式系列之七适配器模式

2016-12-14  本文已影响35人  梦中人在梦中

适配器模式:将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

对于适配器模式,实际上就是一个转接口的概念。比如iphone7的耳塞必须通过转接才能适配,比如水货笔记本的插头必须通过一个转接口才能适配国内的插座等。下面通过代码来具体认识一下适配器模式。

原始接口

//原始接口
public interface OldInterface {
    //原始方法
    public void oldWay();
}
public class OldWay implements OldInterface{
    @Override
    public void oldWay() {
        // TODO Auto-generated method stub
        System.out.println("This is old way.");
    }
}

新接口

//目前的新接口
public interface NewInterface {
    //以新方法去干一件事情
    public void newWay();
}

使用适配器适配原始接口

//通过适配器,使用新接口去调用老接口的方法
public class Adapter implements NewInterface{
    OldInterface old;
    public Adapter(OldInterface old){
        this.old = old;
    }
    @Override
    public void newWay() {
        // TODO Auto-generated method stub
        old.oldWay();
    }
}

测试

public class Test {
    public static void main(String[] args) {
        OldWay old = new OldWay();
        //通过适配,使用新接口去调用老接口
        Adapter adapter = new Adapter(old);
        //打印:This is old way.
        adapter.newWay();
    }
}

通过上述代码,可以很清晰的理解适配器模式的核心思想。适配器模式大量存在与新旧代码兼容,以及如今的前后端分离中的数据接口对接部分。

上一篇:<a href="http://muchstudy.com/2016/12/10/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%B3%BB%E5%88%97%E4%B9%8B%E5%85%AD%E5%91%BD%E4%BB%A4%E6%A8%A1%E5%BC%8F/">设计模式系列之六命令模式</a>
下一篇:<a href="http://muchstudy.com/2016/12/17/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E7%B3%BB%E5%88%97%E4%B9%8B%E5%85%AB%E5%A4%96%E8%A7%82%E6%A8%A1%E5%BC%8F/">设计模式系列之八外观模式</a>

上一篇 下一篇

猜你喜欢

热点阅读