Introduction:
Sometimes you want to decouple the abstraction from its implementation so both of them can be vary independently. Bridge design pattern helps you in implementing this decoupling easily. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes
Example:
static void Main() { // Create Record Set Manager RecordSet customers = new RecordSet(“Jordan”); // Set ConcreteImplementor which is in this case is Customer Data. customers.Data = new CustomersData(); // Exercise the bridge customers.Show(); customers.Next(); customers.Show(); customers.Next(); customers.Show(); customers.Add(“New Customer”); customers.ShowAll(); // Exit Console.ReadKey(); } class RecordSet : RecordSetBase { // Constructor public RecordSet(string CustomerResidancyGroup) : base(CustomerResidancyGroup) { } public override void ShowAll() { Console.WriteLine(); Console.WriteLine(“************************”); base.ShowAll(); Console.WriteLine(“************************”); } } class RecordSetBase { private IDataObject _dataObject; protected string _customerResidancyGroup; public RecordSetBase(string customerResidancyGroup) { this._customerResidancyGroup = customerResidancyGroup; } // Property public IDataObject Data { set { _dataObject = value; } get { return _dataObject; } } public virtual void Next() { _dataObject.NextRecord(); } public virtual void Prior() { _dataObject.PreviousRecord(); } public virtual void Add(string customer) { _dataObject.AddRecord(customer); } public virtual void Delete(string customer) { _dataObject.DeleteRecord(customer); } public virtual void Show() { _dataObject.DisplayRecord(); } public virtual void ShowAll() { Console.WriteLine(“Customer Group: ” + _customerResidancyGroup); _dataObject.DisplayAllRecords(); } } class CustomersData : IDataObject { private List<string> _customers = new List<string>(); private int _current = 0; public CustomersData() { // Loaded from a database _customers.Add(“Customer 1”); _customers.Add(“Customer 2”); _customers.Add(“Customer 3”); _customers.Add(“Customer 4”); _customers.Add(“Customer 5″); } public void NextRecord() { if (_current <= _customers.Count – 1) { _current++; } } public void PreviousRecord() { if (_current > 0) { _current–; } } public void AddRecord(string customer) { _customers.Add(customer); } public void DeleteRecord(string customer) { _customers.Remove(customer); } public void DisplayRecord() { Console.WriteLine(_customers[_current]); } public void DisplayAllRecords() { foreach (string customer in _customers) { Console.WriteLine(” ” + customer); } } } interface IDataObject { void NextRecord(); void PreviousRecord(); void AddRecord(string name); void DeleteRecord(string name); void DisplayRecord(); void DisplayAllRecords(); } |