接口转换器 -- 适配器模式

生活中我们往往需要电源适配器用来转换电压功率,用来给不同的设备供电。
那么在程序中,如果我们有一个实现了A接口的类,如何给需要B接口的方法供电(作为参数传递)呢?
假如我们有一个实现了Callable接口的任务类:

public class Task implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("开始任务");
        int i = 0;
        for (; i < 3; i++) {
            Thread.sleep(1000);
            System.out.println(i + 1);
        }
        System.out.println("结束任务");
        return i;
    }
}

如果我们想用Thread来执行它,那么应该怎么做?

class Client {
    public static void main(String[] args) {
        Task task = new Task();
           // 如何执行呢?
        Thread thread = new Thread();
    }
}

这里我们可以写一个适配器类:

class Adapter implements Runnable {

    private Callable callable = null;

    public Adapter(Callable callable) {
        this.callable = callable;
    }

    @Override
    public void run() {
        try {
            callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

有了这个适配器,我们就做到了将Callable接口转换为Runnable接口,这样就达到了我们的目的,它和我们生活中的电源适配器很像,做到接口转换。
客户端使用如下:

class Client {
    public static void main(String[] args) {
        Task task = new Task();
        Adapter adapter = new Adapter(task);
        Thread thread = new Thread(adapter);
        thread.start();
    }
}

适配器模式是一种结构型模式,由于Java的多重实现,一个适配器还可以适配多个接口,非常实用。

posted @ 2020-07-18 22:00  BarneyMosby  阅读(133)  评论(0)    收藏  举报