适配器模式(Adapter,包装,包装样式):将一个类的接口转换成客户希望的另外一个接口。适配器还分为类适配器(适配器继承自已实现的类)和对象适配器(适配器容纳一个它包裹的类的实例,下面的例子).
类图:
代码:
publicclass Adaptee {
publicvoid sayHello(){
System.out.println("hello");
}
}
publicinterface Target {
publicvoid Request();
}
publicclass Adapter implements Target {
Adaptee adaptee=new Adaptee();
@Override
publicvoid Request() {
adaptee.sayHello();
}
}
publicstaticvoid main(String[] args) {
//创建适配器
Target adapter=new Adapter();
//调用统一接口
adapter.Request();
}
}
优点:令到接口不一样的类可以在一起工作。
缺点:因为Adapter 是为了Adaptee而存在,所以 Adaptee和Adapter类的耦合度很高。
适配器模式适用于对已有类的扩展。在java.io包中用了很多adapter。