适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。
类适配器:
package com.demo.model.adaptor;
public class AdaptorModel {
static class Adaptee{
public void specificRequest(){
System.out.println("我是特殊适配类,有特殊功能");
}
}
static interface Target{
public void request();
}
static class ConcreteTarget implements Target{
@Override
public void request() {
System.out.println("我只是普通类,没有特殊功能");
}
}
static class Adaptor extends Adaptee implements Target{
@Override
public void request() {
// TODO Auto-generated method stub
super.specificRequest();
}
}
public static void main(String[] args) {
Target concreteTarget = new ConcreteTarget();
concreteTarget.request();
Adaptor adaptor = new Adaptor();
adaptor.request();
}
}
对象适配器:
package com.demo.model.adaptor;
public class AdaptorModel {
static class SpaecificAdaptor{
public void specificRequest(){
System.out.println("我是type-c接口,有特殊功能(传输速度有特殊功能)");
}
}
static interface Target{
public void request();
}
static class ConcreteTarget implements Target{
@Override
public void request() {
System.out.println("我只是普通usb3.0接口");
}
}
static class Adaptor implements Target{
private SpaecificAdaptor adaptor;
public Adaptor(SpaecificAdaptor adaptor) {
super();
this.adaptor = adaptor;
}
public void request() {
// TODO Auto-generated method stub
adaptor.specificRequest();
}
}
public static void main(String[] args) {
ConcreteTarget target = new ConcreteTarget();
target.request();
Adaptor adaptor = new Adaptor(new SpaecificAdaptor());
adaptor.request();
}
}
适配器也是包装模式和装饰器模式一样,都具有包装功能。