Friday, 10 January 2014

Adapter design pattern - Implementation

In this article we are going to see the Adapter design pattern and there implementation, Adapter design pattern is  convert a interface of a class in to a client required interface, it is acts as a intermediate layer between the client and the target class.

Class View:
Client Code:

static void Main(string[] args)
{
          
            /*  Adapter Design Pattern */
            ICurrentAdapter two = new TwoPinAdapter();
            ICurrentAdapter three = new ThreePinAdapter();
            List<ICurrentAdapter> adapters = new List<ICurrentAdapter>();
            adapters.Add(two);
            adapters.Add(three);

            foreach(ICurrentAdapter adapter in adapters)
            {
                adapter.Plug();
                Console.WriteLine(" {0} , Power Consumption: {1} ", adapter.GetType().Name, adapter.CurrentConsumption);
            }

            Console.ReadLine();
}



Adapter Design:

 class Current
    {
        private int Amps;

        public Current(int amps)
        {
            Amps = amps;
        }

        public int CurrentConsumption()
        {
            return Amps * 3;
        }

    }


    interface ICurrentAdapter
    {       
        int CurrentConsumption { get; }
       
        void Plug();
    }


    class ThreePinAdapter:ICurrentAdapter
    {
        Current curr;

        public int CurrentConsumption
        {
            get { return curr.CurrentConsumption(); }
        }

        public void Plug()
        {
            curr = new Current(40);
        }
    }

    class TwoPinAdapter:ICurrentAdapter
    {
        Current curr;

        int ICurrentAdapter.CurrentConsumption
        {
            get { return curr.CurrentConsumption(); }
        }

        public void Plug()
        {
            curr = new Current(20);           
        }
       

    }

Output

TwoPinAdapter , Power Consumption: 60
ThreePinAdapter , Power Consumption: 120




From this article we can learn how to implement the Adapter design pattern.

No comments:

Post a Comment