常用的问题:比如手机、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{
@Override
public 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{
@Override
public void ac(Adapter adapter) {
System.out.println("手机充电,电压为"+adapter.convert(this)+"V");
}
}
打印结果:
手机充电,电压为25V
这是我对适配器模式的理解,大家如果觉得小弟哪里讲得不对的地方,还请指针。谢谢