Java设计模式之适配器模式

来源:互联网 发布:mac os x 10.12 cdr 编辑:程序博客网 时间:2024/06/11 01:46

1、使用场景

适配器模式把一个类的接口变换成客户端所期待的另一种接口。以消除由于接口的不匹配所造成类的兼容性问题。适配器模式主要有类的适配器模式、对象的适配器模式两种。

2、两种适配器模式介绍

模式所涉及的角色有:

  目标(Target)角色:这就是所期待得到的接口。

  源(Adapee)角色:现在需要适配的接口。

  适配器(Adaper)角色:适配器类是本模式的核心。适配器把源接口转换成目标接口。(充当中间角色)

1)类的适配器模式

类的适配器模式把适配的类(即源类)的API转换成为目标类的API。

由于是类适配器模式,因此目标不可以是类,适配器不可以是接口而必须是类。

public interface Target {

    /**

     * 这是源类Source也有的方法

     */

    public void sampleOperation1(); 

    /**

     * 这是源类Source没有的方法

     */

    public void sampleOperation2(); 

}

上面是目标角色的源代码,这个接口声明了两个方法:sampleOperation1()sampleOperation2()。而源角色Source是一个具体类,它有一个sampleOperation1()方法,但是没有sampleOperation2()方法。

public class Source{    

    public void sampleOperation1(){}

 

}

 

适配器角色Adapter扩展了Source,同时又实现了目标(Target)接口。由于Source没有提供sampleOperation2()方法,而目标接口又要求这个方法,因此适配器角色Adapter实现了这个方法。

public class Adapter extends Source implements Target {

    /**

     * 由于源类Source 没有方法sampleOperation2()

     * 因此适配器补充上这个方法

     */

    @Override

    public void sampleOperation2() {

        //写相关的代码

    }

}

2)对象的适配器模式

与类的适配器模式一样,对象的适配器模式把被适配的类的API转换成为目标类的API但对象的适配器模式不是使用继承关系连接到Source类,而是使用委派关系连接到Source类。

public class Adapter implements Target{

    private Source source;

    

    public Adapter(Source source){

        this.source = source;

    }

    /**

     * 源类Source有方法sampleOperation1

     * 因此适配器类直接委派即可

     */

    public void sampleOperation1(){

        this.source.sampleOperation1();

    }

    /**

     * 源类Source没有方法sampleOperation2

     * 因此由适配器类需要补充此方法

     */

    public void sampleOperation2(){

        //写相关的代码

    }

}

为使客户端能够使用Source类,需要提供一个包装(Wrapper)Adapter。这个包装类包装了一个Source的实例,从而此包装类能够把Source的APITarget类的API衔接起来。AdapterSource是委派关系,这决定了适配器模式是对象的。

0 0
原创粉丝点击