6. 适配器模式

让原本接口不匹配不能在一起工作的两个类通过适配器类在一起工作

类适配器/对象适配器

/**
 * @author wuyimin
 * @create 2021-07-26 9:56
 * @description 五伏充电器接口
 */
public interface Ivotage5V {
    public int change();
}
/**
 * @author wuyimin
 * @create 2021-07-26 9:54
 * @description 220V供电者类
 */
public class Voltage220V {
    public int chargeFor(){
        int src=220;
        System.out.println("电压=220");
        return src;
    }
}

类适配器

/**
 * @author wuyimin
 * @create 2021-07-26 9:57
 * @description 适配类
 */
public class VoltageAdapter  extends Voltage220V implements Ivotage5V  {
    @Override
    public int change() {
        int src=chargeFor();
        int out=src/44;
        System.out.println("输出电压="+out);
        return out;
    }
}

对象适配器---更加常用

/**
 * @author wuyimin
 * @create 2021-07-26 10:27
 * @description 对象适配器
 */
public class ObjAdapter implements Ivotage5V {
    Voltage220V voltage220V;
    public ObjAdapter( Voltage220V voltage220V){
        this.voltage220V=voltage220V;
    }
    @Override
    public int change() {
        int input = voltage220V.chargeFor();
        int output=input/44;
        System.out.println("输出电压="+output);
        return output;
    }
}
测试类和手机类
public class Phone {
    public void checkBeforeCharge(int out){
        if(out==220){
            System.out.println("爆炸输出");
        }else if(out==5){
            System.out.println("正常输出");
        }
    }
    @Test
    public void test(){
        Phone phone=new Phone();
        Voltage220V src=new Voltage220V();
        VoltageAdapter voltageAdapter=new VoltageAdapter();
        phone.checkBeforeCharge(src.chargeFor());
        phone.checkBeforeCharge(voltageAdapter.change());
    }
    @Test
    public void test02(){
        Phone phone=new Phone();
        Voltage220V src=new Voltage220V();
        ObjAdapter objAdapter=new ObjAdapter(src);
        phone.checkBeforeCharge(objAdapter.change());
    }
}

接口适配器模式--用于不想实现一个接口里的所有方法的情况

public interface MyInterface {
    public void test1();
    public void test2();
    public void test3();
    public void test4();
}
/**
 * @author wuyimin
 * @create 2021-07-26 11:00
 * @description 继承了刚刚接口的类,每个方法都是空方法
 */
public class MyClass implements MyInterface {
    @Override
    public void test1() {

    }

    @Override
    public void test2() {

    }

    @Override
    public void test3() {

    }

    @Override
    public void test4() {

    }
}
public class MyTest extends MyClass {
    @Override
    public void test1() {
        System.out.println("我只想实现方法一");
    }

    @Override
    public void test3() {
        System.out.println("我只想实现方法三");
    }

    public static void main(String[] args) {
        MyTest myTest=new MyTest();
        myTest.test1();
        myTest.test3();
    }
}

 

posted @ 2021-07-26 11:05  一拳超人的逆袭  阅读(51)  评论(0编辑  收藏  举报