适配器模式

在设计模式中,适配器模式(adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。适配器模式使得因接口不兼容而不能在一起工作的类能在一起工作,做法是将类自己的接口包裹在一个已存在的类中。

对象适配器模式

在这种适配器模式中,适配器容纳一个它包裹的类的实例。在这种情况下,适配器调用被包裹对象的物理实体。

UML图

需要适配的类(Adaptee): 需要适配的类或适配者类。

适配器(Adapter): 通过包装一个需要适配的对象,把原接口转换成目标接口

类适配器模式

这种适配器模式下,适配器继承已经实现的类(一般多重继承)。

UML图

代码举例
public class AdapteeToClientAdapter implements Adapter {

    private final Adaptee instance;

    public AdapteeToClientAdapter(final Adaptee instance) {
         this.instance = instance;
    }

    @Override
    public void clientMethod() {
       // call Adaptee's method(s) to implement Client's clientMethod
    }

}
public interface Target {
    public void request();
}
public class Adaptee {
    public void specialRequest() {
        System.out.println("this is special request");
    }
}
public class Adapter implements Target {

    Adaptee adaptee = new Adaptee();

    /* (non-Javadoc)
     * @see com.xub.test.designpattern.adapter.Target#request()
     */
    @Override
    public void request() {
        // TODO Auto-generated method stub
        adaptee.specialRequest();
    }

}
public class Client {
    public static void main(final String[] args) {
        final Target adapter = new Adapter();
        adapter.request();
    }
}

results matching ""

    No results matching ""