设计模式之适配器模式
来源:互联网 发布:mac os x10.7.5下载 编辑:程序博客网 时间:2024/04/28 03:46
适配器模式(Adapter):将一个类的接口转换成客户端(client)希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
Convert the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
这个有类adaptee方法method1()和method2()继承自ownInterface接口,现在有一个接口target有三个方法,需要用到method1()或者method2(),为了不造成耦合,需要一个适配器adapter将adaptee进行适配(java中有直接继承adaptee和 委托 方法),这样client就可以通过target调用adaptee的方法或者是自己实现的another
适配器模式分为类适配器和对象适配器.
类适配器的实现就是通过继承adaaptee实现适配,对象适配器就是用委托的方式实现适配
原始类
// 原始类public class Adaptee implements OwnInterface { public void method1() { System.out.println("原有功能1"); } public void method2() { System.out.println("原有功能2"); }}
// 目标接口,或称为标准接口public interface Target { public void method1(); public void method2(); public void method3();}// 自己的实现public class Another implements Target { public void method1() { System.out.println("自己实现的功能1"); } public void method2() { System.out.println("自己实现的功能2"); } public void method3() { System.out.println("自己实现的功能3"); }}
类适配器
public class Adapter extends Adaptee implements Target{ public void method1() { super.method1(); } public void method2() { super.method2(); } public void method3() { System.out.println("自己实现的功能1"); }}
对象适配器
public class Adapter implements Target{ //委托或者代理 private Adaptee adaptee = new Adaptee(); public void method1() { this.adaptee.method1(); } public void method2() { this.adaptee.method2(); } public void method3() { System.out.println("自己实现的功能1"); }}
client类
public class Client { public static void main(String[] args) { // 使用普通功能类 Target another= new Another(); another.method1(); // 使用特殊功能类,即适配类, // 需要先创建一个被适配类的对象作为参数 Target adapter = new Adapter(); adapter.method1(); }}
0 0
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器
- 设计模式 之 适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- 设计模式之--适配器模式.
- Spring4.3.x 浅析xml配置的解析过程(3)——使用DocumentLoader创建Document对象
- 1057. Stack (30)
- 斜率优化
- Android Studio 关于用户ID信息的保存
- 线程安全
- 设计模式之适配器模式
- Python闭包编程
- |Hdu 2087|KMP|剪花布条
- String StringBuilder StringBuffer
- 我入门的几本书
- 百度大脑和图灵机器人制作一个简单的自动聊天机器人【PHP代码】
- java之自己做一个ThreadLocal
- 如何简单的实现一个富文本,图文混排编辑器
- 使用josm绘制室内地图及路径(二)