適配器:基於現有類所提供的服務,向客戶提供介面,以滿足客戶的期望
《Java設計模式》
一、類適配器:
OtherOperation(已存在所需功能的類):
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:39:18 */public class OtherOperation { public int add(int a, int b){ return a + b; }}
Operation(為所要實現的功能定義介面):
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:40:12 */public interface Operation { public int add(int a, int b);}
OperationAdapter(適配器):
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:40:41 * 對象適配器 */public class OperationAdapter extends OtherOperation implements Operation{}
-----------------------------------------------------------------------------------------------------------------------------------
二、對象適配器:
假如客戶介面期望的功能不止一個,而是多個。
由於java是不能實現多繼承的,所以我們不能通過構建一個適配器,讓他來繼承所有原以完成我們的期望,這時候怎麼辦呢?只能用適配器的另一種實現--對象適配器:
符合java提倡的編程思想之一,即盡量使用彙總不要使用繼承。
OtherAdd和OtherMinus(已存在功能的兩個類):
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:50:14 */public class OtherAdd { public int add(int a, int b){ return a + b; }}
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:50:46 */public class OtherMinus { public int minus(int a, int b){ return a - b; }}
Operation(為所要實現的功能定義介面):
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:51:59 */public interface Operation { public int add(int a, int b); public int minus(int a, int b);}
OperationAdapter(通過適配類的對象來擷取):
/** * @author com.tiantian * @version 建立時間:2012-11-21 下午4:52:36 */public class OperationAdapter implements Operation{ private OtherAdd otherAdd; private OtherMinus otherMinus; public OtherAdd getOtherAdd() { return otherAdd; } public void setOtherAdd(OtherAdd otherAdd) { this.otherAdd = otherAdd; } public OtherMinus getOtherMinus() { return otherMinus; } public void setOtherMinus(OtherMinus otherMinus) { this.otherMinus = otherMinus; } @Override public int add(int a, int b) { return otherAdd.add(a, b); } @Override public int minus(int a, int b) { return otherMinus.minus(a, b); }}