美文网首页
20.适配器模式-对象适配器模式

20.适配器模式-对象适配器模式

作者: 测试员 | 来源:发表于2019-12-15 13:29 被阅读0次

    UML

    对象适配器模式

    代码实现

    需要被适配的类【电源】

    适配类【充电器】

    定义适配功能的接口【变压器功能】

    需要用到适配功能的类【手机-充电时】

    测试类【AdapterTest】


    需要被适配的类【电源】

    package com.yuan.dp.adapter;
    
    /**
     * 提供电源
     * @author Yuan-9826
     */
    public class 电源 {
        /**
         * 提供的电源
         */
       private int POWER = 220;
    
        public int getPOWER() {
            return POWER;
        }
    }
    
    

    适配类【充电器】

    package com.yuan.dp.adapter;
    
    /**
     * 充电器实现类
     *
     * @author Yuan-9826
     */
    public class 充电器 implements 充电功能接口 {
    
        /**
         * 被适配类
         */
        电源 power;
    
        public 充电器(电源 power) {
            this.power = power;
        }
    
        @Override
        public int inToOut() {
            if (power != null) {
                //流入充电器的电压
                System.out.println("输入的电压是 " + power.getPOWER() + "伏");
                try {
                    Thread.sleep(1000);
                    System.out.println("经过了很复杂的处理......");
                    Thread.sleep(1000);
                    int newPower = 5;
                    System.out.println("输出的电压是 " + power + "伏");
                    return newPower;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return -1;
        }
    }
    

    定义适配功能的接口【变压器功能】

    package com.yuan.dp.adapter;
    
    /**
     * 定义充电器应有的功能
     * @author Yuan-9826
     */
    public interface 充电功能接口 {
    
        /**
         * @return 输出电压
         */
        int inToOut();
    }
    
    

    需要用到适配功能的类【手机-充电时】

    package com.yuan.dp.adapter;
    
    /**
     * 手机需要充电 需要直连电源充电
     *
     * @author Yuan-9826
     */
    public class 手机 {
    
        充电器 charger;
    
        public 手机(充电器 charger) {
            this.charger = charger;
        }
    
        /**
         * 充电方法
         */
        void charge() {
    
            int power = charger.inToOut();
            if (power > 5) {
                System.out.println("充电电压 > 5V,手机爆炸了");
            } else if (power < 5) {
                System.out.println("充电电压 < 5V,手机依然没电");
            } else {
                System.out.println("手机用5伏电压正常充电啦~");
            }
        }
    }
    
    

    测试类【AdapterTest】

    package com.yuan.dp.adapter;
    
    public class AdapterTest {
        public static void main(String[] args) {
            /**
             * 自带220v电压
             */
            电源 powerSupply = new 电源();
    
            充电器 charger = new 充电器(powerSupply);
    
            手机 phone = new 手机(charger);
    
            phone.charge();
    
        }
    }
    
    

    相关文章

      网友评论

          本文标题:20.适配器模式-对象适配器模式

          本文链接:https://www.haomeiwen.com/subject/yjiknctx.html