標籤:main author 應該 div logo char sys .com java設計
定義:適配器模式將一個類的介面,轉換成客戶期望的目標介面,使原本由於介面不相容而不能一起工作的那些類可以一起工作。
適配器模式如所示,有4個角色構成,用戶端、目標介面、適配器類Adapter、被適配類Adaptee。
適配器模式實現方式分為組合實現方式(對象適配器)和繼承實現方式(類適配器)
對象適配器實現方式:把被適配類Adaptee作為對象通過適配器類Adapter構造方法傳入,Adapter實現目標介面,修改目標介面(在具體實現方法中調用Adaptee對象的方法),這樣就可以得到目標介面的對象。
類適配器實現方式:適配器類Adapter extends(繼承) Adaptee類 implements(實現) 目標介面(Target interface),在目標介面實現方法中,用this調用父類(adaptee)的方法。
組合模式:就是把被適配類作為一個對象組合到適配器類中,修改目標介面方法。
其步驟:被適配器類通過適配器類構造方法傳入作為其成員變數,Adapter實現目標Target介面,修改目標介面
方法,用戶端類通過Adapter類產生目標介面對象,有目標介面對象用戶端就可以調用其他方法。
(應該是單繼承不相容介面, Java是單繼承的)
只要是把不相容,不匹配的裝換為相容的,我們都稱之為適配器。適配器有很多變體如所示。
執行個體:示範對象適配器和類適配器
情境:我們有個筆記本(用戶端)需要充電,但我們現在只有兩相插座Adaptee,我們需要三相插座,因此我們需要用適配器Adapter把兩相插頭供電Adaptee轉化為三相插頭供電Target。
三相插頭供電介面(Target interface) ThreePlugIf
package com.imooc.pattern.adapter;/** * @author zplogo * 三相插頭介面 */public interface ThreePlugIf { //使用三相電流供電 public void powerWithThreePlug();}
目前存在的兩相插頭供電類(Adaptee) GBTwoPlug
package com.imooc.pattern.adapter;/** * @author zplogo * 國標二相電流插頭 */public class GBTwoPlug { //使用二相電流供電 public void powerWithTwo(){ System.out.println("使用二相電流供電"); }}
組合的方式實現適配器(Adapter) TwoPlugAdapter
package com.imooc.pattern.adapter;/** * @author zplogo * 這個類完成了實現目標介面,同時把被適配類組合到目標介面方法中 */public class TwoPlugAdapter implements ThreePlugIf { private GBTwoPlug gbTwoPlug; public TwoPlugAdapter(GBTwoPlug twoPlug) { this.gbTwoPlug = twoPlug; } //重寫實現介面的方法,把二相的供電能力封裝成三相供電能力 public void powerWithThreePlug() { System.out.println("通過轉換"); gbTwoPlug.powerWithTwo(); }}
繼承的方式實現適配器(Adapter) TwoPlugAdapterExtends
package com.imooc.pattern.adapter;/** * @author zplogo * 繼承的方式實現適配器模式 */public class TwoPlugAdapterExtends extends GBTwoPlug implements ThreePlugIf { public void powerWithThreePlug() { System.out.print("通過繼承適配器類實現 "); this.powerWithTwo(); }}
用戶端類(Client) NoteBook
package com.imooc.pattern.adapter;/** * @author zplogo * 1)筆記本應該有三相插頭這個屬性,調用充電這個動作方法即可充電 * 2)獲得三相插頭對象,需要由實現其介面的適配器類產生,適配器類需要修改其介面方法, * 把二相插頭插頭的供電能力融合到三相供電方法中。 */public class NoteBook { private ThreePlugIf threePlugIf; public NoteBook(ThreePlugIf plug){ this.threePlugIf = plug; } public void charge(){ threePlugIf.powerWithThreePlug(); } public static void main(String[] args) { GBTwoPlug gbTwoPlug = new GBTwoPlug(); ThreePlugIf threePlug = new TwoPlugAdapter(gbTwoPlug); NoteBook noteBook = new NoteBook(threePlug); noteBook.charge(); //通過繼承的方式實現適配器 threePlug = new TwoPlugAdapterExtends(); noteBook = new NoteBook(threePlug); noteBook.charge(); }}
Java設計模式(02--適配器模式)