日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

快速理解桥接模式

發布時間:2025/3/21 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 快速理解桥接模式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

橋接模式的目的是:分離抽象化和實現,使兩者的接口可以不同,目的是分離。

橋接模式的角色有:

實現(Implementor):定義具體行為,具體特征的應用接口。

具體實現(ConcreteImplementor):實現Implementor。

目標接口(Target):?包含實現具體行為、具體特征的Implementor接口或者類。

橋接模式通過在Target里的操作,調用Implementor得操作,達到了Target的抽象與Implementor實現的分離。

如例程:Painter(Target)有畫圖形DrawShape操作,Painter里面包含了Shape(Implementor)接口,Painter的實現類RefinedPainter在自己的DrawShape操作中調用Shape的Draw和Paint操作。


通過例子,在來看看橋接模式起到的作用。在開發的時候設定Target和Implementor采用橋接機制,這樣使得Target和Implementor的后續的接口定義和參數定義上有比較大的靈活度。打個比方,生成洗衣機有兩個部門,一個是水管鏈接器,一個是生產進水管的。水管鏈接器部門就啟動橋接模式,它告訴進水管生產部門,不用擔心連不上,你們生成什么粗細的水管,都可以連上水龍頭。這就在一開始就給生產進水管的部門很多自由度,實現了分離。


橋接模式與適配器模式在代碼實現上是相同的。差別在于適配器模式是已經有一個進水管和家用水龍頭存在了,這時候生產一個接頭來連接進水管和水龍頭,這個接頭就是適配器。橋接是定下生產接頭策略,再讓進水管有開發的自由度。只是先后的問題。


試著寫段程序:

  • //Shape類??
  • abstract?class?Shape{??
  • ????public?abstract?void Draw();??
  • ? ??public?abstract?void Paint();
  • }??
  • //具體工廠(每個具體工廠負責一個具體產品)??
  • class?Circle?extends?Shape{??
  • ????public?void Draw(){??
  • ? ? ? ?printfln("Draw Circle");??
  • ????}??
  • ? ??public?void Paint(){
  • ? ? ? ??printfln("Paint Circle");?
  • ? ? }
  • }??
  • class?Triangle?extends?Shape{??
  • ????public?void Draw(){??
  • ????????printfln("DrawTriangle?");??
  • ????}??
  • ? ??public?void Paint(){
  • ? ? ? ??printfln("PaintTriangle?");
  • ? ? }
  • }??
  • ???
  • public?abstract?class?Painter{
  • ? ??private?Shape?SP;
  • ? ??public?SetImplementor(Shape sp){
  • ? ? ? ?SP = sp;
  • ? ? }
  • ? ??public?void?DrawShape();
  • }
  • public?class?RefinedPainter?extends?Painter
  • ? ??public?void?DrawShape(){
  • ? ? ? ??SP.Draw();
  • ? ? ? ??SP.Paint();
  • ? ? }
  • }
  • //測試??
  • public?class?Test{??
  • ??? ??public?static?void?main(String[]?args){ ?
  • ? ? ? ?RefinedPainter ?refinedPainter?= new?RefinedPainter?();
  • ? ? ? ?refinedPainter.SetImplementor(new?Circle());?
  • ? ? ? ?refinedPainter.DrwaShape();
  • ? ? ? ?refinedPainter.SetImplementor(new?Triangle());
  • ? ? ? ?refinedPainter.DrwaShape();
  • ? ? } ?
  • }
  • 總結

    以上是生活随笔為你收集整理的快速理解桥接模式的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。