之橋接模式

原文:http://www.importnew.com/6857.html

簡單來講,橋接模式是一個兩層的抽象。

橋接模式是用於“把抽象和實現分開,這樣它們就能獨立變化”。 橋接模式使用了封裝、聚合,可以用繼承將不同的功能拆分爲不同的類。

1、橋接模式的故事

電視和遙控器(圖中有錯字)是一個完美展示兩層抽象的例子。你有一個電視機的接口,還有一個遙控器的抽象類。我們都知道,將它們中任何一個定義爲一個具體類都不是好辦法,因爲其它廠家會有不同的實現方法。


2、橋接模式Java示例代碼

首先定義電視機的接口:ITV

1
2
3
4
5
public interface ITV {
    publicvoidon();
    publicvoidoff();
    publicvoidswitchChannel(intchannel);
}

實現三星的 ITV 接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class SamsungTV implementsITV {
    @Override
    publicvoidon() {
        System.out.println("Samsung is turned on.");
    }
 
    @Override
    publicvoidoff() {
        System.out.println("Samsung is turned off.");
    }
 
    @Override
    publicvoidswitchChannel(intchannel) {
        System.out.println("Samsung: channel - "+ channel);
    }
}

再實現索尼的ITV接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class SonyTV implementsITV {
 
    @Override
    publicvoidon() {
        System.out.println("Sony is turned on.");
    }
 
    @Override
    publicvoidoff() {
        System.out.println("Sony is turned off.");
    }
 
    @Override
    publicvoidswitchChannel(intchannel) {
        System.out.println("Sony: channel - "+ channel);
    }
}

遙控器要包含對TV的引用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public abstract class AbstractRemoteControl {
    /**
     * @uml.property  name="tv"
     * @uml.associationEnd 
     */
    privateITV tv;
 
    publicAbstractRemoteControl(ITV tv){
        this.tv = tv;
    }
 
    publicvoidturnOn(){
        tv.on();
    }
 
    publicvoidturnOff(){
        tv.off();
    }
 
    publicvoidsetChannel(intchannel){
        tv.switchChannel(channel);
    }
}

定義遙控器的具體類。

1
2
3
4
5
6
7
8
9
10
11
public class LogitechRemoteControl extendsAbstractRemoteControl {
 
    publicLogitechRemoteControl(ITV tv) {
        super(tv);
    }
 
    publicvoidsetChannelKeyboard(intchannel){
        setChannel(channel);
        System.out.println("Logitech use keyword to set channel.");
    }
}
1
2
3
4
5
6
7
public class Main {
    publicstaticvoid main(String[] args){
        ITV tv =newSonyTV();
        LogitechRemoteControl lrc =newLogitechRemoteControl(tv);
        lrc.setChannelKeyboard(100);   
    }
}

輸出如下:

1
2
Sony: channel – 100
Logitech use keyword tosetchannel.

總結一下, 橋接模式允許兩層實現的抽象,上面的電視機和遙控器就是很好的例子。可見,橋接模式提供了更多的靈活性。

3、Eclipse 平臺上的橋接模式

在Eclipse 架構使用的模式中,橋接模式佔有重要的地位。

發佈了28 篇原創文章 · 獲贊 38 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章