适配器模式分为两种
第一种方式--类适配:
// 220V 电源类 public class Volate220V { //输出220v的电压 public int output220V(){ int src = 220; System.out.println("电压="+src + "伏"); return src; } }
//适配接口 public interface IVoltage5V { public int output5V(); }
//适配器类 public class VoltageAdapter extends Volate220V implements IVoltage5V { @Override public int output5V() { //获得到220v电压 int srcV = output220V(); int dstV = srcV / 44;//转换成5V return dstV; } }
public class Client { public static void main(String[] args){ VoltageAdapter voltageAdapter = new VoltageAdapter(); voltageAdapter.output5V(); } }
//适配接口 public interface IVoltage5V { public int output5V(); }
//被适配的类 public class Volate220V { //输出220v的电压 public int output220V(){ int src = 220; System.out.println("电压="+src + "伏"); return src; } }
//适配器类 public class VoltageAdapter implements IVoltage5V { private Volate220V volate220V;//关联关系-聚合 //通过构造器,传入一个Volate220V实例 public VoltageAdapter(Volate220V volate220V) { this.volate220V = volate220V; } @Override public int output5V() { //获得到220v电压 int dst = 0; if (volate220V != null){ int srcV = volate220V.output220V();//获取220v电压 System.out.println("使用对象适配器,进行适配~"); dst = srcV / 44;//转换成5V System.out.println("适配完成,输出的电压为="+dst); } return dst; } }
public class Client { public static void main(String[] args){ VoltageAdapter voltageAdapter = new VoltageAdapter(new Volate220V()); voltageAdapter.output5V(); } }