一、适配器模式概述
将一个接口转换成客户希望的另外一个接口。(该模式使得原本不兼容的类可以一起工作)
适配器模式是一种结构型模式。
二、适配器模式代码示例
以插座为例,需将双孔充电器用三孔插座充电,需要一个双孔转三孔的适配器
先定义一个双孔充电器
package com.tyyd;
/**
* 2015年4月13日下午4:42:21
* @version 1.0
*/
public interface TwoPlug {
//接口是两孔充电器
public void charge();
}
三孔插座
package com.tyyd;
/**
* 2015年4月13日下午4:42:49
* @version 1.0
*/
public class ThreePlugImpl {
//插座是三孔插座
public void specificCharge() {
System.out.println("三插座充电!");
}
}
设计一个类适配器
package com.tyyd;
/**
* 2015年4月13日下午4:44:13
* @version 1.0
* 通过继承类的为:类适配器
*/
public class AdapterExtends extends ThreePlugImpl implements TwoPlug {
@Override
public void charge() {
System.out.println("通过适配!");
super.specificCharge();
}
}
再设计一个对象适配器,与类适配器功能相同,只是实现方式不同,适配器模式分为类适配器以及对象适配器
package com.tyyd;
/**
* 2015年4月13日下午4:48:08
* @version 1.0
* 通过组合类的为:对象适配器
*/
public class Adapter implements TwoPlug {
ThreePlugImpl threePlugImpl = new ThreePlugImpl();
@Override
public void charge() {
System.out.println("通过适配..");
threePlugImpl.specificCharge();
}
}
最后笔记本调用接口充电,方法还是双孔的方法,充电其实这里用到了三孔的插座进行充电
package com.tyyd;
/**
* 2015年4月13日下午4:46:22
* @version 1.0
*/
public class NoteBook {
public static void main(String[] args) {
System.out.println("新建一个类适配器");
AdapterExtends adapterExtends = new AdapterExtends();
adapterExtends.charge();
System.out.println("新建一个对象适配器");
Adapter adapter = new Adapter();
adapter.charge();
}
}