今天看Android中的下拉列表Spinner中用到ArrayAdapter就学习了下适配器模式。
Adapter模式是将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。其中包括目标接口(Target)、需要适配器的类(Adaptee)和适配器(Adapter)。
看了相关资料后我对是适配器的理解就可拿现实中的电源适配器来举例。假设魅族手机和小米手机USB数据线连接手机的接口是不一样的,而我们只有一个电源适配器,要充电时我们就需要通过这一个电源适配器来连接相应的手机进行充电。
其中电源就是目标接口(Target)、魅族和小米USB数据线就是需要适配器的类(Adaptee)、电源适配器就是适配器(Adapter)。
电源接口类:
package edu.exe.adapter;
public interface PowerInterface {
public void charge();
}
魅族USB数据线类:
package edu.exe.adapter;
public class MeizuUSBLine {
public void MeizuInterface(){
System.out.println("这是魅族手机的连接接口。");
}
}
小米USB数据线类:
package edu.exe.adapter;
public class XiaomiUSBLine {
public void XiaomiInterface(){
System.out.println("这是小米手机的连接接口。");
}
}
电源适配器类:
package edu.exe.adapter;
public class Adapter implements PowerInterface{
MeizuUSBLine meizuUSBLine;
XiaomiUSBLine xiaomiUSBLine;
public Adapter(MeizuUSBLine meizuUSBLine){
this.meizuUSBLine = meizuUSBLine;
}
public Adapter(XiaomiUSBLine xiaomiUSBLine){
this.xiaomiUSBLine = xiaomiUSBLine;
}
@Override
public void charge() {
// TODO Auto-generated method stub
meizuUSBLine.MeizuInterface();
xiaomiUSBLine.XiaomiInterface();
}
}
用户给手机进行充电:
package edu.exe.adapter;
public class MobilePhoneCharged {
public static void main(String[] args) {
//拥有魅族USB数据线
MeizuUSBLine meizuUSBLine = new MeizuUSBLine();
//拥有电源适配器
PowerInterface pInterface = new Adapter(meizuUSBLine);
//给魅族手机充电
pInterface.charge();
}
}
注意:此上是对象适配器源码(类适配器省略)。