橋接模式
橋接模式:不只改變你的實(shí)現(xiàn),也改變你的抽象。
如果有一個(gè)電視廠家,遙控器需要升級,電視也需要修改。這種變化部分的封裝就適合使用橋接模式,橋接模式通過將實(shí)現(xiàn)和抽象放在兩個(gè)不同的類層次中而使它們可以獨(dú)立改變。
設(shè)計(jì)類圖:
?
?
實(shí)現(xiàn)遙控器抽象類
1 public abstract class RemoteControl 2 { 3 public TV tv; 4 public void
SetTV(TV tv) {5 this.tv = tv; 6 } 7 8 public abstract void SetChannel(); 9 }
具體子類
1 public class ConcreteRemote : RemoteControl 2 { 3 public override void
SetChannel()4 { 5 this.tv.TuneChannel(); 6 } 7 }
TV接口類
1 public interface TV 2 { 3 public void TuneChannel(); 4 }
特定TV實(shí)現(xiàn)
1 class PandaTV : TV 2 { 3 public void TuneChannel() 4 { 5
Console.WriteLine("熊貓電視調(diào)頻道"); 6 } 7 } 8 9 10 class ChangHongTV:TV 11 { 12
public void TuneChannel() 13 { 14 Console.WriteLine("長虹電視調(diào)頻道"); 15 } 16 }
測試橋接模式
?
?
?現(xiàn)在有了兩個(gè)層次結(jié)構(gòu),其中一個(gè)是遙控器,另一個(gè)是平臺(tái)特定電視機(jī)實(shí)現(xiàn)。有了橋接的存在,就可以獨(dú)立的改變這兩個(gè)層次。
橋接的有點(diǎn):
1、將實(shí)現(xiàn)予以解耦,讓它和界面之間不再永久綁定。
2、抽象和實(shí)現(xiàn)可以獨(dú)立擴(kuò)展,不會(huì)影響到對方。
3、對于”具體的抽象類“所做的改變,不會(huì)影響到客戶
橋接的用途和缺點(diǎn):
1、適合使用在需要跨平臺(tái)的圖形和窗口系統(tǒng)上。
2、當(dāng)需要用不同的方式改變接口和實(shí)現(xiàn)時(shí),橋接模式很好用。
3、橋接模式的確定時(shí)增加了復(fù)雜度。
熱門工具 換一換