【Java设计模式】结构型模式-适配器模式

2018-10-18  本文已影响0人  灰色孤星

源代码:https://gitee.com/AgentXiao/AdapterPattern

一、原理

1、什么是适配器模式?
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。
2、模式中的角色
– 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
– 需要适配的类(Adaptee):需要适配的类或适配者类。
– 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。

二、实现

我们现在有一部电视机,支持二端插头,只要通电即可正常播放。

/**
 * @ClassName TV
 * @Description 要适配的类,TV,只有二端接口
 * @Author xwd
 * @Date 2018/10/18 22:34
 */
public class TV {
    public void show(int fire,int zero){
        if(fire == 1 && zero == 0){
            System.out.println("电视电源已经接通,正在播放!");
        }
    }
}

但是我们墙上的插座只有三端的,所以我们的目标接口应该是提供一个将三段接口转换为二段接口的方法。

/**
 * @InterfaceName Target
 * @Description 目标接口:三段接口
 * @Author xwd
 * @Date 2018/10/18 22:37
 */
public interface Target {
    public void getTwoFromThree(int fire,int zero,int ground);
}

接下来具体实现适配器,需要注意的是适配器需要和电视联系在一起,可氛围两种方式进行联系。
1)类适配器:适配器继承TV。但是由于类的单继承性,导致适配器不能再继承其他的类。

/**
 * @ClassName Adapter
 * @Description 适配器:将二段接口转接为三段接口(类适配器)
 * @Author xwd
 * @Date 2018/10/18 22:39
 */
public class Adapter extends TV implements Target {
    @Override
    public void getTwoFromThree(int fire,int zero,int ground) {
        super.show(fire,zero);
    }
}

2)对象适配器

/**
 * @ClassName Adapter
 * @Description 适配器:将二段接口转接为三段接口(对象适配器)
 * @Author xwd
 * @Date 2018/10/18 22:39
 */
public class Adapter2 implements Target {
    private TV tv;

    public Adapter2(TV tv) {
        this.tv = tv;
    }

    @Override
    public void getTwoFromThree(int fire,int zero,int ground) {
        tv.show(fire,zero);
    }
}

客户端调用

/**
 * @ClassName client
 * @Description 适配器模式
 * @Author xwd
 * @Date 2018/10/18 22:42
 */
public class client {
    public static void main(String[] args) {
        //类适配器方式下
//        Adapter adapter = new Adapter();
//        adapter.getTwoFromThree(1,0,0);
        //对象适配器方式下
        Adapter2 adapter = new Adapter2(new TV());
        adapter.getTwoFromThree(1,0,0);
    }
}

三、应用

工作中的场景
– 经常用来做旧系统改造和升级
– 如果我们的系统开发之后再也不需要维护,那么很多模式都是没必要的,但是事实却是维护一个系统的代价往往是开发一个系统的数倍。
我们学习中见过的场景
将字节留适配为字符流进行使用
– java.io.InputStreamReader(InputStream)
– java.io.OutputStreamWriter(OutputStream)

上一篇 下一篇

猜你喜欢

热点阅读