using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FactoryMode { // 桥接设计模式 //桥接模式实现了抽象化与实现化的解耦,使它们相互独立互不影响到对方。 /// <summary> /// 笔的抽象类型 /// </summary> public abstract class BridgePatternPen { PenColorDataAccess _penColorDataAccess; public PenColorDataAccess dataAccess { get { return _penColorDataAccess; } set { _penColorDataAccess = value; } } public abstract void Open(int iIndex); public abstract void Close(int iIndex); public abstract void Recycle(int iCount); } public abstract class PenColorDataAccess { //public abstract void PenIndex(int iIndex); //public abstract void PenColorIndex(int iIndex); //public abstract void PenPower(int iVal); public virtual void PenIndex(int iIndex) { Console.WriteLine(iIndex.ToString()); } public virtual void PenColorIndex(int iIndex) { Console.WriteLine(iIndex.ToString()); } public virtual void PenPower(int iVal) { Console.WriteLine(iVal.ToString()); } } public class laserPen : BridgePatternPen { string strLaserPenName = ""; public laserPen(string strName) { strLaserPenName = strName; Console.WriteLine(strName); } public override void Close(int iIndex) { base.dataAccess.PenIndex(iIndex); } public override void Open(int iIndex) { base.dataAccess.PenPower(iIndex); } public override void Recycle(int iCount) { base.dataAccess.PenColorIndex(iCount); } } public class HGPenDataAccess : PenColorDataAccess { int iPower = 0; string[] strPenChannel = {"100", "200", "300", "400", "500" }; string[] strPenColor = { "Red", "Green", "Black", "Blue", "Yellow" }; string strDataAccessName = ""; public HGPenDataAccess (string strName) { strDataAccessName = strName; Console.WriteLine(strDataAccessName); } public override void PenColorIndex(int iIndex) { if (iIndex > strPenColor.Length) { iIndex = 0; } Console.WriteLine(strPenColor[iIndex]); } public override void PenIndex(int iIndex) { if (iIndex>strPenChannel.Length) { iIndex = 0; } for (int i = 0; i < iIndex; i++) { Console.WriteLine(strPenChannel[i]); } } public override void PenPower(int iVal) { iPower = iVal / 2; Console.WriteLine(iPower.ToString()); } } } 使用参考: //===桥接模式 BridgePatternPen bridgePatternPen = new laserPen("JPT_HightPower"); bridgePatternPen.dataAccess =new HGPenDataAccess("JPT_HightPowerDataAccessName"); bridgePatternPen.Open(12); bridgePatternPen.Recycle(2); bridgePatternPen.Close(4); Console.ReadKey();
桥接模式对于抽象和实现可以很好的分离,从而降低修改实现代码时,对整体的影响不大,只需修改相对应的实现部件即可
优点:
1、把抽象接口与其实现解耦。
2、抽象和实现可以独立扩展,不会影响到对方。
3、实现细节对客户端透明,隐藏了具体实现细节;
参考描述:https://www.cnblogs.com/zhili/p/BridgePattern.html
浙公网安备 33010602011771号