适配器模式(Adapter)

来源:互联网 发布:ubuntu卸载anaconda3 编辑:程序博客网 时间:2024/06/02 19:15

1.意图

将一个类的接口转换成客户希望的另外一个接口。 Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

2.特点

适配器模式主要用于兼容原系统使用,在不改动原系统类的情况进行适配
类适配器模式:
1.新建目标接口包含原有类的方法和新方法。
2.新建适配类 继承原有类,实现目标接口。
对象适配器模式:
1.新建适配类实现目标接口,持有原有类作为属性。定义原有类的方法和新方法。
2.通过适配类的实例,调用原有类方法。
接口适配器模式:用于接口的抽象方法多,而具体只关注某些方法。
1.新建适配类实现 原有接口
2.新建具体类 继承适配类,重写某些方法。

3.UML类图

类适配器
类适配器
对象适配器
对象适配器
接口适配器
接口适配器

4.代码

类适配器

/** * Created by lyy on 17-7-12. * 待适配类 */public class Source {    public void method1(){        System.out.println("this old method1");    }}/** * Created by lyy on 17-7-12. * 目标接口 */public interface Targetable {     void method1();     void method2();}/** * Created by lyy on 17-7-12. * 适配类 继承 Source 实现 Targetable */public class Adapter extends Source implements Targetable {    @Override    public void method2() {        System.out.println("this method2 ");    }}

对象适配器

/** * Created by lyy on 17-7-12. * 待适配类 */public class Source {    public void method1(){        System.out.println("this old method1");    }}/** * Created by lyy on 17-7-12. * 目标接口 */public interface Targetable {     void method1();     void method2();}/** * Created by lyy on 17-7-12. * 对象适配器 持有待适配类实例 实现目标接口  */public class AdapterObject implements Targetable{    public Source source = null;    public AdapterObject(Source source){        this.source = source;    }    @Override    public void method1() {        source.method1();    }    @Override    public void method2() {        System.out.println("this method2");    }}

接口适配器

/** * Created by lyy on 17-7-12. * 目标接口 */public interface Sourceable {    void method1();    void method2();}/** * Created by lyy on 17-7-12. * 适配类 实现目标接口 */public class Wrapper implements Sourceable {    @Override    public void method1() {    }    @Override    public void method2() {    }}/** * Created by lyy on 17-7-12. * 具体实现类 */public class SourceSub1 extends Wrapper {    @Override    public void method1() {        System.out.println("this method1");    }}/** * Created by lyy on 17-7-12. * 具体实现类 */public class Sourcesub2 extends Wrapper {    @Override    public void method2() {        System.out.println("this method2");    }}

适配器测试类

public class AdapterTest {    public static void main(String[] args) {        //1,类的适配器 继承 Source 类,实现 Targetable 接口        Targetable adapter = new Adapter();        adapter.method1();        adapter.method2();        //2,对象适配器 持有Source类的实例,实现Targetable 接口        Source source = new Source();        Targetable targetable = new AdapterObject(source);        targetable.method1();        targetable.method2();        //3,接口适配器 接口方法太多 适配器类实现接口,子类各自实现想要的方法        Sourceable sourceable1 = new SourceSub1();        Sourceable sourceable2 = new Sourcesub2();        sourceable1.method1();        sourceable2.method2();    }}