设计模式之适配器模式

来源:互联网 发布:ps dr3插件for mac 编辑:程序博客网 时间:2024/06/08 13:37

 适配器模式

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

        主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式

   
  类的适配器模式

public class Source {    public void method1(){        System.out.println("this is original method!");    }}

      适配的接口:

public interface Targetable {    /* 与原类中的方法相同 */    public void method1();    /* 新类的方法 */    public void method2();}
    
   实现类:

public class Adapter extends Source implements Targetable{    @Override    public void method2() {        System.out.println("this is the targetable method!");    }}
   

对象的适配模式

   基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Source类,而是持有Source类的实例,以达到解决兼容性的问题

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 the targetable method!");    }    @Override    public void method1() {        source.method1();    }}


接口的适配器模式

     第三种适配器模式是接口的适配器模式,接口的适配器是这样的:有时我们写的一个接口中有多个抽象方法,当我们写该接口的实现类时,必须实现该接口的所有方法,这明显有时比较浪费,因为并不是所有的方法都是我们需要的,有时只需要某一些,此处为了解决这个问题,我们引入了接口的适配器模式,借助于一个抽象类,该抽象类实现了该接口,实现了所有的方法,而我们不和原始的接口打交道,只和该抽象类取得联系,所以我们写一个类,继承该抽象类,重写我们需要的方法就行。



public interface Sourceable {    public void method1();    public void method2();}
public abstract  class Wrapper2 implements Sourceable {    public void method1(){}    public void method2(){}}

public class SourceSub1 extends Wrapper2 {    //通过中转的抽象类  可以让这里想用到接口的哪个方法 就只重写哪个方法    public void method1(){        System.out.println("the sourceable interface's first Sub1!");    }    public class SourceSub2 extends Wrapper2 {        public void method2(){            System.out.println("the sourceable interface's second Sub2!");        }    }}

 * 接口适配模式测试 */public class WrapperTest {    public static void main(String[] args) {        Sourceable source1 = new SourceSub1();        //虽然SourceSub1只重写了method1方法,但可以调用到抽象类的方法        source1.method1();        source1.method2();    }}





0 0
原创粉丝点击