设计模式之Adapter
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
定義:
將兩個(gè)不兼容的類糾合在一起使用,屬于結(jié)構(gòu)型模式,需要有Adaptee(被適配者)和Adaptor(適配器)兩個(gè)身份.
eg:
假設(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)在有一個(gè)應(yīng)用,需要既打方形樁,又打圓形樁.那么我們需要將這兩個(gè)沒有關(guān)系的類綜合應(yīng)用.假設(shè)RoundPeg我們沒有源代碼,或源代碼我們不想修改,那么我們使用Adapter來實(shí)現(xiàn)這個(gè)應(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,是被適配者.PegAdapter是Adapter,將Adaptee(被適配者RoundPeg)和Target(目標(biāo)SquarePeg)進(jìn)行適配.實(shí)際上這是將組合方法(composition)和繼承(inheritance)方法綜合運(yùn)用.
PegAdapter首先繼承SquarePeg,然后使用new的組合生成對(duì)象方式,生成RoundPeg的對(duì)象roundPeg,再重載父類insert()方法。從這里,你也了解使用new生成對(duì)象和使用extends繼承生成對(duì)象的不同,前者無需對(duì)原來的類修改,甚至無需要知道其內(nèi)部結(jié)構(gòu)和源代碼.
如果你有些Java使用的經(jīng)驗(yàn),已經(jīng)發(fā)現(xiàn),這種模式經(jīng)常使用。
進(jìn)一步使用
上面的PegAdapter是繼承了SquarePeg,如果我們需要兩邊繼承,即繼承SquarePeg 又繼承RoundPeg,因?yàn)镴ava中不允許多繼承,但是我們可以實(shí)現(xiàn)(implements)兩個(gè)接口(interface)
public interface IRoundPeg{
public void insertIntoHole(String msg);
}
public interface ISquarePeg{
public void insert(String str);
}
下面是新的RoundPeg 和SquarePeg, 除了實(shí)現(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);}
}
轉(zhuǎn)載于:https://my.oschina.net/u/219582/blog/59456
總結(jié)
以上是生活随笔為你收集整理的设计模式之Adapter的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 元数据与IL简介
- 下一篇: 簡單編譯內核 linux kernel