java 適配器模式

來源:互聯網
上載者:User

適配器:基於現有類所提供的服務,向客戶提供介面,以滿足客戶的期望

                                                       《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);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.