一、適配器模式,就像是你的電腦的電源一樣,可以將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(); } }
