常见设计模式之【适配器模式】
来源:互联网 发布:有hao123软件 编辑:程序博客网 时间:2024/06/02 05:42
常用的问题:比如手机、Mp3、电脑等的充电器,转换接头都相当于一个适配器。类似这种数据转换的马上想到适配器模式
package MyAdapter;/** *@Description: 适配器模式 *@author Potter *@date 2012-8-14 下午11:17:12 *@version V1.0 */public class App {public static void main(String[] args) {Adapter adapter=new Adapter();adapter.setPower(new Power(220));Device phone=new Phone();phone.ac(adapter);}}
电源类:
package MyAdapter;/** *@Description: 电源 *@author Potter *@date 2012-8-14 下午11:20:35 *@version V1.0 */public class Power {int v;//电压public Power(int v){this.v=v;}}
适配器类:
package MyAdapter;/** *@Description: *@author Potter *@date 2012-8-14 下午11:18:10 *@version V1.0 */public class Adapter {Power power;/**转变成合适的电源给设备充电**/public int convert(Device device){if(device instanceof Mp3){power.v=20;}else if(device instanceof Phone){power.v=25;}return power.v;}public Power getPower() {return power;}public void setPower(Power power) {this.power = power;}}
设备抽象类:
package MyAdapter;/** *@Description: *@author Potter *@date 2012-8-15 下午09:59:58 *@version V1.0 */public abstract class Device {/**充电 * @param p 电压 */public abstract void ac(Adapter adapter);}
具体类MP3:
package MyAdapter;/** *@Description: *@author Potter *@date 2012-8-14 下午11:18:39 *@version V1.0 */public class Mp3 extends Device{@Overridepublic void ac(Adapter adapter) {System.out.println("map3 充电,电压为"+adapter.convert(this)+"V");}}
具体类Phone:
package MyAdapter;/** *@Description: *@author Potter *@date 2012-8-14 下午11:18:29 *@version V1.0 */public class Phone extends Device{@Overridepublic void ac(Adapter adapter) {System.out.println("手机充电,电压为"+adapter.convert(this)+"V");}}
打印结果:
手机充电,电压为25V
这是我对适配器模式的理解,大家如果觉得小弟哪里讲得不对的地方,还请指针。谢谢
- 常见设计模式之【适配器模式】
- Android 进阶之路:常见设计模式之适配器模式
- Java中常见的设计模式之适配器模式
- PHP常见的设计模式之:适配器模式
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器
- 设计模式 之 适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式之适配器
- 设计模式 之 适配器模式
- 设计模式之适配器模式
- 设计模式之适配器模式
- Google C++编程风格指南(非常有用)
- poj1125 - Stockbroker Grapevine
- 字符驱动设计----mini2440LED驱动设计之路
- Android上dip、dp、px、sp等单位说明
- Linux设备模型(中)之上层容器 (转)
- 常见设计模式之【适配器模式】
- windows下的dll文件和linux下的.so文件
- maven 配置
- Android 报错 - 无法解析类型 java.lang.Object。从必需的 .class 文件间接引用了它
- 动态数据类型 笔记
- android学习之一 工程目录认识
- socket编程:SO_REUSEADDR例解
- 小满的博客cocos2d-x
- Qt 类简介之 Qt QApplication 类