結構型模式-橋接模式

概述

將抽象部分與它的實現部分分離,使它們都可以獨立地變化。

適用性

1.你不希望在抽象和它的實現部分之間有一個固定的綁定關係。
例如這種情況可能是因爲,在程序運行時刻實現部分應可以被選擇或者切換。

2.類的抽象以及它的實現都應該可以通過生成子類的方法加以擴充。
這時Bridge模式使你可以對不同的抽象接口和實現部分進行組合,並分別對它們進行擴充。

3.對一個抽象的實現部分的修改應對客戶不產生影響,即客戶的代碼不必重新編譯。

4.正如在意圖一節的第一個類圖中所示的那樣,有許多類要生成。
這樣一種類層次結構說明你必須將一個對象分解成兩個部分。

5.你想在多個對象間共享實現(可能使用引用計數),但同時要求客戶並不知道這一點。

參與者

1.Abstraction
定義抽象類的接口。
維護一個指向Implementor類型對象的指針。

2.RefinedAbstraction
擴充由Abstraction定義的接口。

3.Implementor
定義實現類的接口,該接口不一定要與Abstraction的接口完全一致。
事實上這兩個接口可以完全不同。
一般來講,Implementor接口僅提供基本操作,而Abstraction則定義了基於這些基本操作的較高層次的操作。

4.ConcreteImplementor
實現Implementor接口並定義它的具體實現。

類圖

代碼實現

1.Abstraction
public abstract class Person {

    private Clothing clothing;
    
    private String type;

    public Clothing getClothing() {
        return clothing;
    }

    public void setClothing() {
        this.clothing = ClothingFactory.getClothing();
    }
    
    public void setType(String type) {
        this.type = type;
    }
    
    public String getType() {
        return this.type;
    }
    
    public abstract void dress();
}

2.RefinedAbstraction
public class Man extends Person {
    
    public Man() {
        setType("男人");
    }
    
    public void dress() {
        Clothing clothing = getClothing();
        clothing.personDressCloth(this);
    }
}
public class Lady extends Person {

    public Lady() {
        setType("女人");
    }
    
    public void dress() {
        Clothing clothing = getClothing();
        clothing.personDressCloth(this);
    }
}

3.Implementor
public abstract class Clothing {

    public abstract void personDressCloth(Person person);
}

4.ConcreteImplementor
public class Jacket extends Clothing {

    public void personDressCloth(Person person) {
        System.out.println(person.getType() + "穿馬甲");
    }
}

public class Trouser extends Clothing {

    public void personDressCloth(Person person) {
        System.out.println(person.getType() + "穿褲子");
    }
}
5.Test
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);
    }
}
6.執行結果
男人穿馬甲
男人穿褲子
女人穿馬甲
女人穿褲子

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章