
簡(jiǎn)介
橋接模式其定義是將抽象部分與實(shí)現(xiàn)部分分離,是它們可以獨(dú)立進(jìn)行變化。根據(jù)名字和定義可以簡(jiǎn)單的理解這種結(jié)構(gòu),中間有一個(gè)起到橋梁作用的東西,這樣被這座橋連接的兩端就可以發(fā)生改變,卻又不會(huì)相會(huì)影響。
還有一點(diǎn),橋接模式還可以用于樹(shù)狀類(lèi)之間的解耦。

橋接模式.png
- Abstraction:抽象部分,該類(lèi)保持一個(gè)實(shí)現(xiàn)的對(duì)象引用,抽象部分中的方法需要調(diào)用實(shí)現(xiàn)部分的對(duì)象來(lái)實(shí)現(xiàn)
- RefinedAbstraction:抽象部分的具體實(shí)現(xiàn),該類(lèi)一般是對(duì)抽象部分的方法進(jìn)行完善和擴(kuò)展
- Implementor:實(shí)現(xiàn)部分,可以是接口或者抽象類(lèi)。該類(lèi)一般情況下會(huì)定義基本操作,提供給抽象部分來(lái)實(shí)現(xiàn)業(yè)務(wù)方法
- ConcreteImplementorA:實(shí)現(xiàn)部分的具體實(shí)現(xiàn),完善實(shí)現(xiàn)部分的具體邏輯。
簡(jiǎn)單實(shí)現(xiàn)
抽象部分
public abstract class Abstraction {
//聲明私有成員變量
private Implementor implementor;
public Abstraction(Implementor implementor){
this.implementor = implementor;
}
public void operation(){
implementor.operationImpl();
}
}
public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
public void refinedOperation(){
//對(duì)Abstraction中的方法進(jìn)行擴(kuò)展
operation();
}
}
實(shí)現(xiàn)部分
public interface Implementor {
public void operationImpl();
}
public class ConcreteImplementorA implements Implementor {
@Override
public void operationImpl() {
//具體實(shí)現(xiàn)
}
}
public class ConcreteImplementorB implements Implementor {
@Override
public void operationImpl() {
//具體實(shí)現(xiàn)
}
}
客戶(hù)端部分
public class Client {
public static void main(String[] args) {
ConcreteImplementorA implementorA = new ConcreteImplementorA();
RefinedAbstraction refinedAbstractionA = new RefinedAbstraction(implementorA);
refinedAbstractionA.refinedOperation();
ConcreteImplementorB implementorB = new ConcreteImplementorB();
RefinedAbstraction refinedAbstractionB = new RefinedAbstraction(implementorB);
refinedAbstractionB.refinedOperation();
}
}
總結(jié)
優(yōu)點(diǎn)
- 實(shí)現(xiàn)了抽象和實(shí)現(xiàn)部分的分離。橋接模式分離了抽象部分和實(shí)現(xiàn)部分,從而極大的提供了系統(tǒng)的靈活性,讓抽象部分和實(shí)現(xiàn)部分獨(dú)立開(kāi)來(lái),分別定義接口,這有助于系統(tǒng)進(jìn)行分層設(shè)計(jì),從而產(chǎn)生更好的結(jié)構(gòu)化系統(tǒng)。對(duì)于系統(tǒng)的高層部分,只需要知道抽象部分和實(shí)現(xiàn)部分的接口就可以了。
- 更好的可擴(kuò)展性。由于橋接模式把抽象部分和實(shí)現(xiàn)部分分離了,從而分別定義接口,這就使得抽象部分和實(shí)現(xiàn)部分可以分別獨(dú)立擴(kuò)展,而不會(huì)相互影響,大大的提供了系統(tǒng)的可擴(kuò)展性。
- 可動(dòng)態(tài)的切換實(shí)現(xiàn)。由于橋接模式實(shí)現(xiàn)了抽象和實(shí)現(xiàn)的分離,所以在實(shí)現(xiàn)橋接模式時(shí),就可以實(shí)現(xiàn)動(dòng)態(tài)的選擇和使用具體的實(shí)現(xiàn)。
- 實(shí)現(xiàn)細(xì)節(jié)對(duì)客戶(hù)端透明,可以對(duì)用戶(hù)隱藏實(shí)現(xiàn)細(xì)節(jié)。
缺點(diǎn)
- 橋接模式的引入增加了系統(tǒng)的理解和設(shè)計(jì)難度,由于聚合關(guān)聯(lián)關(guān)系建立在抽象層,要求開(kāi)發(fā)者針對(duì)抽象進(jìn)行設(shè)計(jì)和編程。
- 橋接模式要求正確識(shí)別出系統(tǒng)中兩個(gè)獨(dú)立變化的維度,因此其使用范圍有一定的局限性。