五、适配器模式

2020-04-01  本文已影响0人  奔跑吧老王

适配器模式分类

类适配器 集成

对象适配器 组合替代集成 符合合成复用原则

接口适配器

本文展示的为对象适配器模式,话不多说上图:

image.png

220伏电压类

public class Voltage220 {


    public Integer outPut(){

        System.out.println(220+"伏");
        return 220;
    }
}

5伏接口类

public interface Voltage5 {
    int outputFive();
}

适配器类

@Data
public class VoltageAdapter implements Voltage5{


    private Voltage220 voltage220;
    @Override
    public int outputFive() {
        Integer integer = voltage220.outPut();
        return integer/44;
    }
}

手机调用类des

@Data
public class Phone implements  Voltage5{

    private Voltage5 voltage5;
    @Override
    public int outputFive() {
        int i = voltage5.outputFive();
        System.out.println("输出电压为:"+i);
        return i;
    }
}

上下文操作类:

public class Context {

    public static void main(String[] args) {
        Phone phone=new Phone();
        VoltageAdapter voltageAdapter = new VoltageAdapter();
        voltageAdapter.setVoltage220(new Voltage220());
        phone.setVoltage5(voltageAdapter);
        phone.outputFive();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读