适配器模式:当前接口不满足用户想要的结果并且又不想改动现有的接口时,适配器模式就可以有用武之地了。
代码:
1.业务接口
public interface Adaptee {
/**
* 交强险
*/
public void compulsory();
}
2.接口实现
/**
* adaptee
*/
public class AdapteeImpl implements Adaptee {
@Override
public void compulsory() {
System.out.println("交强险缴纳完成");
}
}
3.新增业务接口
/**
* target
*/
public interface Enhancement {
void vehicleDamage();
}
4.adapter实现 根据具体的业务实现
/**
* adaptee :需要被适配的对象或类型,相当于插头。
* adapter : 连接目标和源的中间对象,相当于插头转换器。
* target :期待得到的目标,相当于插座。
*/
public class Adapter implements Enhancement {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
/**
* 强制缴纳交强险
*/
public void compulsory() {
this.adaptee.compulsory();
}
/**
* 车损险可选
*/
@Override
public void vehicleDamage() {
System.out.println("车损险缴纳完成");
}
public void all() {
this.adaptee.compulsory();
this.vehicleDamage();
}
}
5.测试
public class Main {
public static void main(String[] args) {
Adapter adapter = new Adapter(new AdapteeImpl());
adapter.compulsory();
adapter.vehicleDamage();
adapter.all();
}
}
spring中大量的使用了适配器模式,比如aop,springmvc等,可以去看spring源码