适配器模式

适配器模式定义

适配器模式将一个类的接口,转换成客户期望的另一个接口,适配器让原本接口不兼容的类可以合作无间。
对象的适配

package com.zheng.nie.adapter;
/**
 * @author: niezheng1
 * @Date: 2019/1/3 16:33
 *
 * 被适配的类,220V的输出电源
 */
public class AC220 {

    public int output(){
        System.out.println("在中国输出220V电压");
        return 220;
    }

}

package com.zheng.nie.adapter;

/**
 * @author: niezheng1
 * @Date: 2019/1/3 16:38
 */
public interface AC5V {

    void output();

}

package com.zheng.nie.adapter;

/**
 * @author: niezheng1
 * @Date: 2019/1/3 16:40
 *
 * 适配类 将220v转换为5v,持有被适配对象的引用
 *
 */
public class PowerAdapter implements AC5V {

    private AC220 ac220;

    public PowerAdapter(AC220 ac220) {
        this.ac220 = ac220;
    }

    @Override
    public void output() {
        System.out.println("适配之后电压为"+ac220.output()/44+"V");
    }
}

package com.zheng.nie.adapter;

/**
 * @author: niezheng1
 * @Date: 2019/1/3 16:42
 */
public class App {


    public static void main(String[] args) {
        AC5V ac5V = new PowerAdapter(new AC220());
        ac5V.output();
    }

}

运行结果如下:

在中国输出220V电压
适配之后电压为5V

你可能感兴趣的:(适配器模式)