轉載請註明出處:http://blog.csdn.net/l1028386804/article/details/45457969
一、概述
將抽象部分與它的實現部分分離,使它們都可以獨立地變化。 二、適用性
1.你不希望在抽象和它的實現部分之間有一個固定的綁定關係。 例如這種情況可能是因為,在程式運行時刻實現部分應可以被選擇或者切換。
2.類的抽象以及它的實現都應該可以通過產生子類的方法加以擴充。 這時Bridge模式使你可以對不同的抽象介面和實現部分進行組合,並分別對它們進行擴充。
3.對一個抽象的實現部分的修改應對客戶不產生影響,即客戶的代碼不必重新編譯。
4.正如在意圖一節的第一個類圖中所示的那樣,有許多類要產生。 這樣一種類階層說明你必須將一個對象分解成兩個部分。 5.你想在多個對象間共用實現(可能使用引用計數),但同時要求客戶並不知道這一點。 三、參與者
1.Abstraction
定義抽象類別的介面。 維護一個指向Implementor類型對象的指標。
2.RefinedAbstraction
擴充由Abstraction定義的介面。
3.Implementor
定義實作類別的介面,該介面不一定要與Abstraction的介面完全一致。 事實上這兩個介面可以完全不同。 一般來講,Implementor介面僅提供基本操作,而Abstraction則定義了基於這些基本操作的較高層次的操作。
4.ConcreteImplementor
實現Implementor介面並定義它的具體實現。 四、類圖
五、樣本
Abstraction
package com.lyz.design.bridge;/** * 定義Abstraction Person類 * @author liuyazhuang * */public abstract class Person {private Clothing clothing;private String type;public Clothing getClothing() {return clothing;}public void setClothing(Clothing clothing) {this.clothing = clothing;}public void setType(String type) {this.type = type;}public String getType() {return this.type;}public abstract void dress();}
RefinedAbstraction
package com.lyz.design.bridge;/** * 定義RefinedAbstraction類Man * @author liuyazhuang * */public class Man extends Person { public Man() { setType("男人"); } public void dress() { Clothing clothing = getClothing(); clothing.personDressCloth(this); }}
package com.lyz.design.bridge;/** * 定義RefinedAbstraction類Lady * @author liuyazhuang * */public class Lady extends Person { public Lady() { setType("女人"); } public void dress() { Clothing clothing = getClothing(); clothing.personDressCloth(this); }}
Implementor
package com.lyz.design.bridge;/** * 定義Implementor 類Clothing * @author liuyazhuang * */public abstract class Clothing { public abstract void personDressCloth(Person person);}
ConcreteImplementor
package com.lyz.design.bridge;/** * 定義ConcreteImplementor類Jacket * @author liuyazhuang * */public class Jacket extends Clothing { public void personDressCloth(Person person) { System.out.println(person.getType() + "穿馬甲"); }}
package com.lyz.design.bridge;/** * 定義ConcreteImplementor類 Trouser * @author liuyazhuang * */public class Trouser extends Clothing { public void personDressCloth(Person person) { System.out.println(person.getType() + "穿褲子"); }}
Test
package com.lyz.design.bridge;/** * 測試類別 * @author liuyazhuang * */public class Test {public static void main(String[] args) {Person man = new Man();Person lady = new Lady();Clothing jacket = new Jacket();Clothing trouser = new Trouser();jacket.personDressCloth(man);trouser.personDressCloth(man);jacket.personDressCloth(lady);trouser.personDressCloth(lady);}}
result
男人穿馬甲男人穿褲子女人穿馬甲女人穿褲子