博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
适配器模式
阅读量:6926 次
发布时间:2019-06-27

本文共 1880 字,大约阅读时间需要 6 分钟。

hot3.png

    适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。适配器模式主要分为2种实现:1.继承待适配类实现目标接口、2.复合待适配类实现目标接口。

1.1、继承待适配类实现目标接口

    有一个待适配的Source类,目标接口是Targetable。通过Adapter类,将Source的功能扩展到Targetable里。

package com.model.structure;public class Source {    public void method1() {          System.out.println("this is original method!");      }  }
package com.model.structure;public interface Targetable {    /* 与原类中的方法相同 */    public void method1();    /* 新类的方法 */    public void method2();}

适配器类:

package com.model.structure;public class Adapter extends Source implements Targetable {    public void method2() {        System.out.println("this is the targetable method!");    }}
package com.model.structure;public class AdapterTest {    public static void main(String[] args) {        Targetable target = new Adapter();        target.method1();        target.method2();    }}

AdapterTest的运行结果:

1.2、复合待适配类实现目标接口

    不继承Source类,而是持有Source类的实例。

package com.model.structure;public class Source {    public void method1() {          System.out.println("this is original method!");      }  }
package com.model.structure;public interface Targetable {    /* 与原类中的方法相同 */    public void method1();    /* 新类的方法 */    public void method2();}​

​适配器类:

package com.model.structure;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();    }}
package com.model.structure;public class AdapterTest {    public static void main(String[] args) {        Source source = new Source();        Targetable target = new Wrapper(source);        target.method1();        target.method2();    }}

运行结果:

转载于:https://my.oschina.net/langwanghuangshifu/blog/1933967

你可能感兴趣的文章
V-rep学习笔记:main script and child scripts
查看>>
浅拷贝(在进行当中一个对象的运算时开辟新的空间)
查看>>
HDU Today HDU杭电2112【Dijkstra || SPFA】
查看>>
通过docker-compose构建ghost博客(二)
查看>>
Hive merge(小文件合并)
查看>>
拖拽系列二、利用JS面向对象OOP思想实现拖拽封装
查看>>
Atitit 华为基本法 attilax读后感
查看>>
简略的帧动画
查看>>
JNI/NDK开发指南(2)
查看>>
IOS-2-C语言和Objective-C语言衔接学习资料
查看>>
Head First设计模式之观察者模式
查看>>
jquery控制display属性为none或block
查看>>
Nginx配置项优化(转载)
查看>>
数字签名是什么?
查看>>
TCP server 为什么一个端口可以建立多个连接?
查看>>
VC dimension(Vapnik-Chervonenkis dimension)
查看>>
操作系统 之 哈希表 Linux 内核 应用浅析
查看>>
JavaScript使用正則表達式
查看>>
数据库系统学习(四)- 关系模型之关系代数
查看>>
nor flash 和nand flash 傻傻分不清楚
查看>>