关于java:Java中的适配器模式

适配器模式简介

  • 适配器模式是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它联合了两个独立接口的性能。
  • 这种模式波及到一个繁多的类,该类负责退出独立的或不兼容的接口性能。

类模式

要被适配的类TV和类Wire
//要被适配的类:电视
public class TV {
    //电视剧须要一个电源适配器,就能够供电,开机
    public void open(IPowerAdapter iPowerAdapter) {
        //关上电视,须要电,须要连贯电线,须要一个电源适配器
        iPowerAdapter.power();
    }
}

//要被适配接入的类:电线
public class Wire {
    public void supply() {
        System.out.println("供上电了...");
    }
}
电源适配器接口IPowerAdapter
//电源适配器接口
public interface IPowerAdapter {
    //供电
    void power();
}
电线和电视机适配器类TVPowerAdapter(通过继承形式)
//真正的适配器,一端连贯电线,一端连贯电视
public class TVPowerAdapter extends Wire implements IPowerAdapter {
    @Override
    public void power() {
        super.supply();//有电了
    }
}
测试类
public class Test {
    public static void main(String[] args) {
        TV tv = new TV();//电视
        TVPowerAdapter tvPowerAdapter = new TVPowerAdapter();//电源适配器
        Wire wire = new Wire();//电线

        tv.open(tvPowerAdapter);

        /**
         * 输入后果:
         * 供上电了...
         */
    }
}
测试后果
供上电了...

组合模式(举荐应用)

要被适配的类TV和类Wire
//要被适配的类:电视
public class TV {
    //电视剧须要一个电源适配器,就能够供电,开机
    public void open(IPowerAdapter iPowerAdapter) {
        //关上电视,须要电,须要连贯电线,须要一个电源适配器
        iPowerAdapter.power();
    }
}

//要被适配接入的类:电线
public class Wire {
    public void supply() {
        System.out.println("供上电了...");
    }
}
电源适配器接口IPowerAdapter
//电源适配器接口
public interface IPowerAdapter {
    //供电
    void power();
}
电线和电视机适配器类TVPowerAdapter(通过组合形式)
//真正的适配器,一端连贯电线,一端连贯电视
public class TVPowerAdapter implements IPowerAdapter {
    private Wire wire;

    public TVPowerAdapter(Wire wire) {
        this.wire = wire;
    }

    @Override
    public void power() {
        wire.supply();//有电了
    }
}
测试类
public class Test {
    public static void main(String[] args) {
        TV tv = new TV();//电视
        Wire wire = new Wire();//电线
        TVPowerAdapter tvPowerAdapter = new TVPowerAdapter(wire);//电源适配器

        tv.open(tvPowerAdapter);

        /**
         * 输入后果:
         * 供上电了...
         */
    }
}
测试后果
供上电了...

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理