原创内容,转载请注明出处
适配器模式,顾名思义,主要是解决实际类与目标类接口不一致的问题。现实生活中最典型的例子是电源适配器,适配不同电压,以防止损坏电器设备。
适配器模式分两种一种是类适配器模式,一种是对象适配器模式。类适配器模式是适配类继承被适配类并实现目标接口,对象适配器模式是适配类中有被适配类的成员变量。
UML类图表示如下
类适配器如下
对象适配器如下
创建目标接口类Target,代码如下
package com.test.designermodel.adaptermodel;
public interface Target {
void process();
}
创建被适配类Adaptee,代码如下
package com.test.designermodel.adaptermodel;
public class Adaptee {
public void execute(){
System.out.println("----执行处理----");
}
}
创建类适配器类AdapterClass,代码如下
package com.test.designermodel.adaptermodel;
/**
* 类适配器模式
* @author Alan
*
*/
public class AdapterClass extends Adaptee implements Target {
public void process() {
System.out.println("类适配器开始适配");
this.execute();
}
}
创建对象适配器类AdapterObject,代码如下
package com.test.designermodel.adaptermodel;
/**
* 对象适配器模式
* @author Alan
*
*/
public class AdapterObject implements Target {
private Adaptee adaptee;
public AdapterObject(Adaptee adaptee){
this.adaptee=adaptee;
}
public void process() {
System.out.println("对象适配器开始适配");
adaptee.execute();
}
}
编写Junit测试代码如下
/**
* 适配器模式
*/
@Test
public void testAdapterModel(){
//类适配器模式
new AdapterClass().process();
//对象适配器模式
new AdapterObject(new Adaptee()).process();
}
测试结果如下
如上可以看出类适配器模式相对与对象适配器模式而言,类适配器AdapterClass只能适配当前被适配者Adaptee,不能适配到其子类,对象适配器AdapterObject可以适配被适配者Adaptee的所有子类(因为Adaptee是AdapterObject类中的成员变量),对象适配器模式扩展性相对更好。
源代码如附件