1. 程式人生 > 其它 >設計模式(七)橋接模式

設計模式(七)橋接模式

1、定義

  橋接模式是將抽象部分與它的實現部分分離,使它們都對立地變化。它是一種物件結構模式,又稱為柄體(Handle and Body)模式或介面(Interface)模式。

2、優劣分析

(1)好處分析

  • 橋接模式類似於多繼承方案,但是多繼承方案違背了類的單一職責原則,複用性比較差,類的個數也非常多,橋接模式是比多繼承方案更好的解決方法。極大地減少了子類的個數,從而降低管理和維護的成本;
  • 橋接模式提高了系統的可擴充套件性,在兩個變化維度中任意擴充套件一個維度,都不需要修改原有系統,符合開閉原則,就像一座橋,可以把兩個變化的維度連結起來。

(2)劣勢分析

  • 橋接模式的引入會增加系統的理解與設計維度,由於聚合關聯關係建立在抽象層,要求開發者針對抽象進行設計與程式設計;
  • 橋接模式要求正確識別出系統中兩個獨立變化的維度,因此其使用範圍具有一定的侷限性。

3、最佳實踐

  • 如果一個系統需要在構建的抽象化角色和具體角色之間增加更多的靈活性,避免在兩個層次之間建立靜態的繼承聯絡,通過橋接模式可以使他們在抽象層建立一個關聯關係。抽象化角色和實現化結束可以以繼承的方式獨立擴充套件而互不影響,在程式執行時,可以動態將一個抽象化子類的物件和一個實現化子類的物件進行組合,即系統需要對抽象化角色和實現化角色進行動態耦合;
  • 一個類存在兩個獨立變化的維度,且這兩個維度都需要進行擴充套件;
  • 雖然在系統中使用繼承是沒有問題的,但是由於抽象化角色和具體化角色需要獨立變化,設計要求需要獨立管理這兩者。對於那些不需要使用繼承或因為多層次繼承導致系統類的個數急劇增加的系統,橋接模式尤為適用。

4、場景:

  • Java語言通過Java虛擬機器實現了平臺的無關性;
  • AWT中的Peer架構;
  • JDBC驅動程式也是橋接模式的應用之一。

5、類圖

6、程式碼例項

1 /**
2  * @author it-小林
3  * @desc 品牌
4  * @date 2021年07月21日 19:41
5  */
6 public interface Brand {
7 
8     void info();
9 }
 1 /**
 2  * @author it-小林
 3  * @desc 蘋果品牌
 4  * @date 2021年07月21日 19:43
 5  */
 6 public
class Apple implements Brand{ 7 @Override 8 public void info() { 9 System.out.print("蘋果"); 10 } 11 }
 1 /**
 2  * @author it-小林
 3  * @desc 聯想品牌
 4  * @date 2021年07月21日 19:42
 5  */
 6 public class Lenovo implements Brand{
 7 
 8     @Override
 9     public void info() {
10         System.out.print("聯想");
11     }
12 }
 1 /**
 2  * @author it-小林
 3  * @desc 抽象的電腦型別類
 4  * @date 2021年07月21日 19:44
 5  */
 6 public abstract class Computer {
 7 
 8     //組合, 品牌
 9     protected Brand brand;
10 
11     public Computer(Brand brand) {
12         this.brand = brand;
13     }
14 
15     public void info(){
16         //自帶品牌
17         brand.info();
18     }
19 }
 1 /**
 2  * @author it-小林
 3  * @desc
 4  * @date 2021年07月21日 19:46
 5  */
 6 public class Desktop extends Computer{
 7     public Desktop(Brand brand) {
 8         super(brand);
 9     }
10 
11     @Override
12     public void info() {
13         super.info();
14         System.out.println("桌上型電腦");
15     }
16 }
 1 /**
 2  * @author it-小林
 3  * @desc
 4  * @date 2021年07月21日 19:48
 5  */
 6 public class Laptop extends Computer{
 7 
 8     public Laptop(Brand brand) {
 9         super(brand);
10     }
11 
12     @Override
13     public void info() {
14         super.info();
15         System.out.println("筆記本");
16     }
17 }
 1 /**
 2  * @author it-小林
 3  * @desc
 4  * @date 2021年07月21日 19:49
 5  */
 6 public class Test {
 7 
 8     public static void main(String[] args) {
 9         //蘋果筆記本
10         Computer computer = new Laptop(new Apple());
11         computer.info();
12 
13         //聯想桌上型電腦
14         Computer computer2 = new Desktop(new Lenovo());
15         computer2.info();
16     }
17 }

執行結果截圖

如本文有侵權行為,請及時與本人聯絡,多多包涵! 小生初出茅廬,多多指教!

本文來自部落格園,作者:it-小林,轉載請註明原文連結:https://www.cnblogs.com/linruitao/p/15041100.html