24.JAVA编程之适配器模式

适配器模式(Adapter)

将一个类的接口转换成客户希望的另一个接口,适配器模式使得原本由于接口不兼容而不能在一起工作的那些类可以在一起工作
示例代码:
PowerA的对象能够使用work()方法,而PowerB不能使用work()方法,所以要写一个Adapter 适配器,implements PowerA,

public class Demo {

    public static void main(String[] args) {
        PowerA powerA = new PowerAImpl();
        work(powerA);
        PowerB powerB = new PowerBImpl();
        //接口不兼容
        //work(powerB);
        Adapter d = new Adapter(powerB);
        work(d);

    }

    public static void work(PowerA a){
        System.out.println("正在连接");
        a.insert();
        System.out.println("工作结束");
    }

}

//适配器
class  Adapter implements PowerA{
    private PowerB powerB;

    public Adapter(PowerB powerB){
        this.powerB = powerB;
    }

    @Override
    public void insert() {
        powerB.connet();
    }
}

interface PowerB{
    public void connet();
}

class PowerBImpl implements PowerB{

    @Override
    public void connet() {
        System.out.println("电源B开始工作");
    }
}

interface PowerA{
    public void insert();
}

class PowerAImpl implements PowerA{

    @Override
    public void insert() {
        System.out.println("电源A开始工作");
    }
}

运行效果:

还有一种适配器:
定义的接口中方法比较多,一个类实现这个接口的时候,需要重写所有方法,如果这个类用不到所有方法,可以写一个适配器,让类继承这个适配器,要用到哪个方法就重写哪个方法。

interface Animal{
    public void sing();
    public void cry();
    public void run();
    public void swim();
}
//适配器2
abstract class AnimalFunction{
    public void sing() {

    }

    public void cry() {

    }

    public void run() {

    }

    public void swim() {

    }
}
class Dog extends AnimalFunction{
//要用哪个方法就重写哪个方法
    public void run() {

    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容