场景描述:
1、 在系统设计时,发现类的继承有N层时,但不能确定是否会更改继承来的共性,可以考虑使用桥梁模式。
2、类图描述:桥梁模式是抽象和实现的解耦,使得两者可以独立地变化。
3、程序实现举例(C#):
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BridgeApp { //实现话角色 public interface IRealizeInfactor { void Work(); void Sleep(); void Eat(); } //具体实现化角色 public class RealizeClassA : IRealizeInfactor { public void Work() { Console.WriteLine("实现类A工作"); Console.Read(); } public virtual void Sleep() { Console.WriteLine("实现类A睡觉"); Console.Read(); } public void Eat() { Console.WriteLine("实现类A吃饭"); Console.Read(); } } public class RealizeClassB : IRealizeInfactor { public void Work() { Console.WriteLine("实现类B工作"); Console.Read(); } public void Sleep() { Console.WriteLine("实现类B睡觉"); Console.Read(); } public void Eat() { Console.WriteLine("实现类B吃饭"); Console.Read(); } } //抽象化角色 public abstract class Abstractor { private IRealizeInfactor irealizeInfactor; public Abstractor(IRealizeInfactor _irealizeInfactor) { this.irealizeInfactor = _irealizeInfactor; } public virtual void DoThings() { this.irealizeInfactor.Work(); this.irealizeInfactor.Sleep(); } //获得实现化角色 public IRealizeInfactor GetIRealizeInfactor() { return irealizeInfactor; } } //具体抽象化角色 public class RefinedAbstrctor : Abstractor { //覆写构造函数 public RefinedAbstrctor(IRealizeInfactor _irealizeInfactor) : base(_irealizeInfactor) { } //修正父类 public override void DoThings() { /*业务处理具体实行*/ base.DoThings(); base.GetIRealizeInfactor().Eat(); } } }
4、程序调用:
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BridgeApp { class Program { static void Main(string[] args) { IRealizeInfactor infactor = new RealizeClassB(); RefinedAbstrctor reAbstractor = new RefinedAbstrctor(infactor); reAbstractor.DoThings(); infactor = new RealizeClassA(); reAbstractor = new RefinedAbstrctor(infactor); reAbstractor.DoThings(); } } }