设计模式的代码:https://github.com/Aerozb/design_patterns
实际应用:看springmvc适配器模式---HandlerAdapter
对象适配器:通过聚合方式,而不是直接继承
案例:220V电压通过充电器转成5V给手机充电
public class Voltage220V {
public int output(){
System.out.println("220v");
return 220;
}
}
public interface IVolatege5V {
public int output5V();
}
public class VoltageAdapter implements IVolatege5V {
private Voltage220V voltage220V;
public VoltageAdapter(Voltage220V voltage220V) {
this.voltage220V = voltage220V;
}
@Override
public int output5V() {
int v = 0;
if (null != voltage220V) {
v = voltage220V.output();
v = v / 44;
System.out.println(v + "V");
}
return v;
}
}
public class Phone {
private IVolatege5V iVolatege5V;
public Phone(IVolatege5V iVolatege5V) {
this.iVolatege5V = iVolatege5V;
}
public void charge() {
int v = iVolatege5V.output5V();
if (v == 5) {
System.out.println("充电成功" + v + "V");
}else {
System.out.println("充电失败");
}
}
}
public class Client {
public static void main(String[] args) {
VoltageAdapter voltageAdapter=new VoltageAdapter(new Voltage220V());
Phone phone=new Phone(voltageAdapter);
phone.charge();
}
}
结果:
220v
5V
充电成功5V
小结:VoltageAdapter 继承IVolatege5V 接口,聚合Voltage220V 类,手机类聚合IVolatege5V接口,调用output5V()方法,就会调用实现类的方法(即适配器),适配器会进行转换,用户端手机充电只要调用charge()方法充电就行,new的时候要把适配器加进去(就是5V的实现类)