Object Oriented Programming Patterns for Geeks

The Bridge Pattern

 

namespace ooppatterns
{
    using System;

    internal class Program
    {
        private static void Main( string[] args )
        {
            IRequiresImplementor ab = new Consumer();

            // Add initiatal implementation...
            ab.Implementor = new ImplementABC();
            ab.UseImplementation();

            // Change implemention...
            ab.Implementor = new ImplementXYZ();
            ab.UseImplementation();

            Console.ReadLine();
        }
    }

    interface IRequiresImplementor
    {
        IImplementor Implementor { set;}

        void UseImplementation();
    }

    class Consumer : IRequiresImplementor
    {
        private IImplementor _implementor;

        public IImplementor Implementor
        {
            set { this._implementor = value; }
        }

        public void UseImplementation()
        {
            if ( this._implementor == null )
                throw new NullReferenceException();

            this._implementor.DoSomething();
        }
    }

    interface IImplementor
    {
        void DoSomething();
    }

    class ImplementABC : IImplementor
    {
        public void DoSomething()
        {
            Console.WriteLine( "Do Something ABC" );
        }
    }

    class ImplementXYZ : IImplementor
    {
        public void DoSomething()
        {
            Console.WriteLine( "Do Something XYZ" );
        }
    }
}