zoukankan      html  css  js  c++  java
  • 设计模式笔记--适配器

    举个栗子:
    笔记本要充电,电压必须稳定在20V左右,家用电压是220V左右,直接接上大概会爆掉。这就需要电压适配器。

    └── adapter
        ├── ChargerAdapter.java
        ├── Computer.java
        ├── ComputerNew.java
        └── Test.java
    
    package com.xh.pattern.adapter;
    
    /**
     * 没有适配器的电脑
     * Created by root on 3/15/18.
     */
    public class Computer {
    
        /**
         * 充电
         *
         * @param voltage 电压
         */
        public void charge(int voltage) {
            if (18 <= voltage && voltage <= 20) {
                System.out.println("电压标准,正在充电...");
            } else {
                System.out.println("非标准电压,不能充电!");
            }
    
        }
    }
    
    package com.xh.pattern.adapter;
    
    /**
     * 适配器
     * Created by root on 3/15/18.
     */
    public class ChargerAdapter {
    
        /**
         * 变压
         *
         * @param voltage 电压
         */
        public int changeVoltage(int voltage) {
            System.out.println("电压是" + voltage + "V,改变为19V");
            return 19;
    
        }
    }
    
    package com.xh.pattern.adapter;
    
    /**
     * Created by root on 3/15/18.
     */
    public class ComputerNew extends Computer {
    
        private static ChargerAdapter chargerAdapter = new ChargerAdapter();
    
        /**
         * 充电
         *
         * @param voltage 电压
         */
        public void charge(int voltage) {
            voltage = chargerAdapter.changeVoltage(voltage);
            super.charge(voltage);
        }
    }
    
    package com.xh.pattern.adapter;
    
    /**
     * Created by root on 3/15/18.
     */
    public class Test {
        public static void main(String[] args) {
            Computer computer = new Computer();
            computer.charge(220);
            System.out.println("====================");
            computer = new ComputerNew();
            computer.charge(220);
        }
    }
    
    非标准电压,不能充电!
    ====================
    电压是220V,改变为19V
    电压标准,正在充电...
    
  • 相关阅读:
    Linux常用几种shell
    opencv中snake的调用方法示例
    GIT 常用命令手册
    偏最小二乘法回归(Partial Least Squares Regression)
    镜头的参数指标
    Git详解Git分支
    tab选项卡,不带自动切换定时器
    setTimeout和setInterval
    tab选项卡,带自动播放
    动态添加,删除class样式
  • 原文地址:https://www.cnblogs.com/lanqie/p/8574400.html
Copyright © 2011-2022 走看看