设计模式——适配器模式(Adapter)
2019-07-14 01:53发布
生成海报
文章目录
代码:GitHub |
适配器设计模式(笔记本+电源+插座)
0. UML结构图
1. Code示例
1.1 笔记本
public class Laptop {
private double electricity;
public void charge(Target target) {
System.out.println("开始充电");
while (electricity < 100) {
electricity += target.transport();
System.out.println("电量已有 " + electricity);
}
System.out.println("充电完成");
}
}
1.2 电源插座
public class PowerOutlet {
public int getElectricity() {
return 10;
}
}
1.3 电源适配器
public class PowerAdapter implements Target{
private PowerOutlet outlet;
public PowerAdapter(PowerOutlet outlet) {
this.outlet = outlet;
}
@Override
public double transport() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return outlet.getElectricity() * 0.5;
}
}
1. 4电源接口
public interface Target {
double transport();
}
2. Test示例
public class AdapterTest {
public static void main(String[] args) {
Laptop laptop = new Laptop();
PowerOutlet outlet = new PowerOutlet();
PowerAdapter adapter = new PowerAdapter(outlet);
laptop.charge(adapter);
}
}
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮