一、适配器模式,就像是你的电脑的电源一样,可以将220v的电压转化为你电脑能够承受的电压,又如从美国带回来的电器,需要一个适配电源将电压220v改成110v
二、适配器的两种模式:类的适配器和对象适配器
三、类适配器(主要使用继承方式来适配)
1、类适配器模式
AmericaPower.java(美国的电源头是三个脚的)
package com.adapterModel.classAdapter; public interface AmericaPower { public void threeStep(); }
APower.java(美国电源插头的具体实现类)
package com.adapterModel.classAdapter; public class APower implements AmericaPower { @Override public void threeStep() { System.out.println("我是三角的电源"); } }
ChinaPower.java(中国电源插头的接口类)
package com.adapterModel.classAdapter; public interface ChinaPower { public void twoStep(); }
CPower.java(中国插头的具体实现类)
package com.adapterModel.classAdapter; public class CPower extends APower implements ChinaPower { @Override public void twoStep() { this.threeStep(); } }
测试类
package com.adapterModel.classAdapter; public class Test { public static void main(String[] args) { ChinaPower chinaPower = new CPower(); //插入两脚的电源线,可以适配三角的插头。 chinaPower.twoStep(); } }
2、对象适配器
AmericaPower.java
package com.adapterModel.instanceAdapter; public interface AmericaPower { public void threeStep(); }
APower.java
package com.adapterModel.instanceAdapter; public class APower implements AmericaPower { @Override public void threeStep() { System.out.println("我是三角的电源"); } }
ChinaPower.java
package com.adapterModel.instanceAdapter; public interface ChinaPower { public void twoStep(); }
CPower.java(内有一个美国插头的实例对象)
package com.adapterModel.instanceAdapter; public class CPower implements ChinaPower { private AmericaPower ap = new APower(); @Override public void twoStep() { ap.threeStep(); } }
测试类
package com.adapterModel.instanceAdapter; public class Test { public static void main(String[] args) { ChinaPower chinaPower = new CPower(); //插入两脚的电源线,可以适配三角的插头。 chinaPower.twoStep(); } }