【设计模式】适配器模式浅析

  • 应用场景

       已知条件:类A中包含方法A,接口B中包含方法B,当前应用需要调用方法A,但是只能调用到方法B。

  问:如何在当前应用中通过调用接口B的方法B,来完成调用方法A的逻辑。

  答:这个时候可以采用适配器模式。

    【类适配器】定义一个适配器类,继承类A的同时实现接口B,在重写的方法B中调用父类的方法A,这样在具体应用中可以直接使用该适配器类调用方法B,而实际上具体承担逻辑的是父类A中的方法A;

    【对象适配器】定义一个适配器类,实现接口B的同时,持有类A的实例,在重写的方法B中通过实例A调用方法A来实现。

  具体代码可参考如下示例。

  • 类适配器示例代码
//可处理逻辑的类
public class Adaptee {

    public void sampleA(){
        System.out.println("受改造者:可处理逻辑");
    }

}
//可以调用的接口
public interface Target {

    public void sampleB();

}
//适配器类
public class AdapterClass extends Adaptee implements Target{

    public void sampleB(){
        sampleA();
    }

}
//调用逻辑
public class TestAdapter {
    public static void main(String[] args){

        Target target = new AdapterClass();
        target.sampleB();

    }
}

 

  • 对象适配器示例代码
public class Adaptee {
    public void sampleA(){
        System.out.println("受改造者:可处理逻辑");
    }
}

public interface Target {
    public void sampleB();
}


public class AdapterObject implements Target{
    Adaptee adaptee ;

    public AdapterObject(Adaptee adaptee){
        this.adaptee = adaptee;
    }

    public void sampleB(){
        adaptee.sampleA();
    }

}

public class TestAdapter {
    public static void main(String[] args){

        Target target1 = new AdapterObject(new Adaptee());
        target1.sampleB();
    }
}

 

posted @ 2018-09-20 15:54  季末花开  阅读(110)  评论(0编辑  收藏  举报