日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

設(shè)計模式之Adapter(適配器)

 HaiLan 2006-09-14

設(shè)計模式之Adapter(適配器)

適配器模式定義:
將兩個不兼容的類糾合在一起使用,屬于結(jié)構(gòu)型模式,需要有Adaptee(被適配者)Adaptor(適配器)兩個身份.

為何使用?
我們經(jīng)常碰到要將兩個沒有關(guān)系的類組合在一起使用,第一解決方案是:修改各自類的接口,但是如果我們沒有源代碼,或者,我們不愿意為了一個應(yīng)用而修改各自的接口。怎么辦?

使用Adapter,在這兩種接口之間創(chuàng)建一個混合接口(混血兒).

如何使用?
實現(xiàn)Adapter方式,其實"think in Java""類再生"一節(jié)中已經(jīng)提到,有兩種方式:組合(composition)和繼承(inheritance).


假設(shè)我們要打樁,有兩種類:方形樁 圓形樁.
public class SquarePeg{
  
public void insert(String str){
    
System.out.println("SquarePeg insert():"+str);
  }

}

public class RoundPeg{
  public void insertIntohole(String msg){
    
System.out.println("RoundPeg insertIntoHole():"+msg);
}
}

現(xiàn)在有一個應(yīng)用,需要既打方形樁,又打圓形樁.那么我們需要將這兩個沒有關(guān)系的類綜合應(yīng)用.假設(shè)RoundPeg我們沒有源代碼,或源代碼我們不想修改,那么我們使用Adapter來實現(xiàn)這個應(yīng)用:

public class PegAdapter extends SquarePeg{

  private RoundPeg roundPeg;

  public PegAdapter(RoundPeg peg)(this.roundPeg=peg;)

  public void insert(String str){ roundPeg.insertIntoHole(str);}

}

在上面代碼中,RoundPeg屬于Adaptee,是被適配者.PegAdapterAdapter,Adaptee(被適配者RoundPeg)Target(目標(biāo)SquarePeg)進(jìn)行適配.實際上這是將組合方法(composition)和繼承(inheritance)方法綜合運用.

PegAdapter首先繼承SquarePeg,然后使用new的組合生成對象方式,生成RoundPeg的對象roundPeg,再重載父類insert()方法。從這里,你也了解使用new生成對象和使用extends繼承生成對象的不同,前者無需對原來的類修改,甚至無需要知道其內(nèi)部結(jié)構(gòu)和源代碼.

如果你有些Java使用的經(jīng)驗,已經(jīng)發(fā)現(xiàn),這種模式經(jīng)常使用。

進(jìn)一步使用
上面的PegAdapter是繼承了SquarePeg,如果我們需要兩邊繼承,即繼承SquarePeg 又繼承RoundPeg,因為Java中不允許多繼承,但是我們可以實現(xiàn)(implements)兩個接口(interface)

public interface IRoundPeg{
  public void insertIntoHole(String msg);

}

public interface ISquarePeg{
  public void insert(String str);

}

下面是新的RoundPeg SquarePeg, 除了實現(xiàn)接口這一區(qū)別,和上面的沒什么區(qū)別。
public class SquarePeg implements ISquarePeg{
  public void insert(String str){
    
System.out.println("SquarePeg insert():"+str);
  }

}

public class RoundPeg implements IRoundPeg{
  public void insertIntohole(String msg){
    
System.out.println("RoundPeg insertIntoHole():"+msg);
  
}
}

下面是新的PegAdapter,叫做two-way adapter:

public class PegAdapter implements IRoundPeg,ISquarePeg{

  private RoundPeg roundPeg;
  
private SquarePeg squarePeg;

  // 構(gòu)造方法

  public PegAdapter(RoundPeg peg){this.roundPeg=peg;}
  // 構(gòu)造方法

  public PegAdapter(SquarePeg peg)(this.squarePeg=peg;)

  public void insert(String str){ roundPeg.insertIntoHole(str);}

}

還有一種叫Pluggable Adapters,可以動態(tài)的獲取幾個adapters中一個。使用Reflection技術(shù),可以動態(tài)的發(fā)現(xiàn)類中的Public方法。

設(shè)計模式如何在具體項目中應(yīng)用見《Java實用系統(tǒng)開發(fā)指南》

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多