介紹
橋接模式 (Bridge)將抽象部分與實(shí)現(xiàn)部分分離,使它們都可以獨(dú)立的變化。
橋接模式是一種結(jié)構(gòu)式模式。
結(jié)構(gòu)
代碼實(shí)現(xiàn)
Implementor : 定義實(shí)現(xiàn)接口。
1
2
3
4
|
interface Implementor { // 實(shí)現(xiàn)抽象部分需要的某些具體功能 public void operationImpl(); } |
Abstraction : 定義抽象接口。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
abstract class Abstraction { // 持有一個(gè) Implementor 對(duì)象,形成聚合關(guān)系 protected Implementor implementor; public Abstraction(Implementor implementor) { this .implementor = implementor; } // 可能需要轉(zhuǎn)調(diào)實(shí)現(xiàn)部分的具體實(shí)現(xiàn) public void operation() { implementor.operationImpl(); } } |
ConcreteImplementor : 實(shí)現(xiàn) Implementor 中定義的接口。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class ConcreteImplementorA implements Implementor { @Override public void operationImpl() { // 真正的實(shí)現(xiàn) System.out.println( "具體實(shí)現(xiàn)A" ); } } class ConcreteImplementorB implements Implementor { @Override public void operationImpl() { // 真正的實(shí)現(xiàn) System.out.println( "具體實(shí)現(xiàn)B" ); } } |
RefinedAbstraction : 擴(kuò)展 Abstraction 類。
1
2
3
4
5
6
7
8
9
10
11
12
|
class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor implementor) { super (implementor); } public void otherOperation() { // 實(shí)現(xiàn)一定的功能,可能會(huì)使用具體實(shí)現(xiàn)部分的實(shí)現(xiàn)方法, // 但是本方法更大的可能是使用 Abstraction 中定義的方法, // 通過(guò)組合使用 Abstraction 中定義的方法來(lái)完成更多的功能。 } } |
測(cè)試代碼
1
2
3
4
5
6
7
8
|
public class BridgePattern { public static void main(String[] args) { Implementor implementor = new ConcreteImplementorA(); RefinedAbstraction abstraction = new RefinedAbstraction(implementor); abstraction.operation(); abstraction.otherOperation(); } } |
運(yùn)行結(jié)果
具體實(shí)現(xiàn)A
其他操作
應(yīng)用場(chǎng)景
1、如果你不希望在抽象和實(shí)現(xiàn)部分采用固定的綁定關(guān)系,可以采用橋接模式,來(lái)把抽象和實(shí)現(xiàn)部分分開(kāi),
然后在程序運(yùn)行期間來(lái)動(dòng)態(tài)的設(shè)置抽象部分需要用到的具體的實(shí)現(xiàn),還可以動(dòng)態(tài)切換具體的實(shí)現(xiàn)。
2、如果出現(xiàn)抽象部分和實(shí)現(xiàn)部分都應(yīng)該可以擴(kuò)展的情況,可以采用橋接模式,讓抽象部分和實(shí)現(xiàn)部分可以
獨(dú)立的變化,從而可以靈活的進(jìn)行單獨(dú)擴(kuò)展,而不是攪在一起,擴(kuò)展一邊會(huì)影響到另一邊。
3、如果希望實(shí)現(xiàn)部分的修改,不會(huì)對(duì)客戶產(chǎn)生影響,可以采用橋接模式,客戶是面向抽象的接口在運(yùn)行,
實(shí)現(xiàn)部分的修改,可以獨(dú)立于抽象部分,也就不會(huì)對(duì)客戶產(chǎn)生影響了,也可以說(shuō)對(duì)客戶是透明的。
4、如果采用繼承的實(shí)現(xiàn)方案,會(huì)導(dǎo)致產(chǎn)生很多子類,對(duì)于這種情況,可以考慮采用橋接模式,分析功能變化的原因,看看是否能分離成不同的緯度,然后通過(guò)橋接模式來(lái)分離它們,從而減少子類的數(shù)目。
要點(diǎn)
如果一個(gè)系統(tǒng)需要在構(gòu)件的抽象化角色和具體化角色之間增加更多的靈活性,避免在兩個(gè)層次之間建立靜態(tài)的聯(lián)系。
抽象化角色和具體化角色都應(yīng)該可以被子類擴(kuò)展。在這種情況下,橋接模式可以靈活地組合不同的抽象化角色和具體化角色,并獨(dú)立化地?cái)U(kuò)展。
設(shè)計(jì)要求實(shí)現(xiàn)化角色的任何改變不應(yīng)當(dāng)影響客戶端,或者說(shuō)實(shí)現(xiàn)化角色的改變對(duì)客戶端是完全透明的。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/jingmoxukong/p/4224661.html