设计模式笔记--适配器
举个栗子:
笔记本要充电,电压必须稳定在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
电压标准,正在充电...