适配器模式
组合方式实现
/**
* 三相插座接口
*/
public interface IThreePlug {
void powerWithThree();
}
public class GBTwoPlug {
public void powerWithTwo (){
System.out.println("使用二相电流供电" );
}
}
public class TwoPlugAdapter implements IThreePlug {
private GBTwoPlug plug;
public TwoPlugAdapter (GBTwoPlug plug) {
super ();
this .plug = plug;
}
@Override
public void powerWithThree () {
System.out.println("通过组合方式转化" );
plug.powerWithTwo();
}
}
public class NoteBook {
private IThreePlug plug;
public NoteBook (IThreePlug plug){
this .plug=plug;
}
/**
* 使用插座充电
*/
public void charge (){
plug.powerWithThree();
}
}
public static void main (String[] args) {
GBTwoPlug two = new GBTwoPlug();
IThreePlug plug = new TwoPlugAdapter(two);
NoteBook noteBook = new NoteBook(plug);
noteBook.charge();
}
继承方式实现
/**
* 采用继承方式的插座适配器
*/
public class TwoPlugClassAdapter extends GBTwoPlug implements IThreePlug {
@Override
public void powerWithThree () {
System.out.println("借助继承方式转化" );
this .powerWithTwo();
}
}
public static void main (String[] args) {
TwoPlugClassAdapter adapter = new TwoPlugClassAdapter();
NoteBook nb = new NoteBook(adapter);
nb.charge();
}