二十三种设计模式之:适配器模式

      适配器模式将某个类的接口转换成客户期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性的问题。主要分为三类:类的适配器模式,对象的适配器模式,接口的适配器模式。

1.类的适配器模式

实现思想是:有一个类Source,拥有一个方法method1,待适配;目标接口是Targetable,通过Adapter类,将Source类的功能扩展到Targetable中,具体代码如下:

public class Source{

  public void method1(){

    System.out.println("This is Source's method1");

  }

}

public interface Targetable{

  public void method1();

  public void method2();

}

public class Adapter extends Source implements Targetable{

  public void method1(){

    System.out.println("This is Adapter's method1");

  }

  @Override

  public void method2(){

    System.out.println("This is Adapter's method2");

  }

}

测试类:

public class AdapterTest{

  public static void main(String [] args){

    Targetable targetable = new Adapter();

    targetable.method1();

    targetable.method2();

  }

}

2.对象的适配器模式

public class Wrapper implements Targetable{

  private Source source;

  public Wrapper(Source source){

    super();

    this.source = source;

  }

  @Override

  public void method2(){

    System.out.println("This is Targetable's method2");

  }

  @Override

  public void method1(){

    source.method1();

  }

}

测试类:

public class AdapterTest{

  public static void main(String [] args){

    Source source = new Source();

    Targetable wrapper = new Wrapper(source);

    wrapper.method1();

    wrapper.method2();

  }

}

3.接口的适配器模式

UML图如下:

接口的适配器模式的原理是:通过抽象类Wrapper实现Sourceable接口的方法,然后其他的类可以通过抽象类Wrapper来选择性的实现接口的方法。

代码如下:

public Interface Sourceable(){

  public void method1();

  public void method2();

}

public abstract class Wrapper implements Sourceable{

  @Override

  public void method1(){}

  @Override

  public void method2(){}

}

public class SourceSub1 extends Wrapper{

  public void method1(){

    System.out.println("This is the Interface's first Sub1!");

  }

  public void method2(){

    System.out.println("This is the Interface's seconds Sub2!");

  }

}

main方法:

public class Wrapper{

  public static void main(String [] args){

    Sourceable sourceSub1 = new SourceSub1();

    sourceable sourceSub2 = new SourceSub2();

    sourceSub1.method1();

    sourceSub1.method2();

    sourceSub2.method1();

    sourceSub2.method2();

  }

}

原文地址:https://www.cnblogs.com/qadyyj/p/5645963.html