Friday, June 14, 2013

Adapter design pattern in C#

As it’s name suggest ,it is used to make compatible two class. Have a look of my code.    In my Class2 I did not implement IAdaptor() interface . Where I have implement that interface in Class1. Now my Class2 contains one Push() function. But my client part(Here main function) want to invoke my Push() function but it’s not interested to use function name Push(). Still it’s want to call my Push() function by name Add().
Hmm, It’s a problem right ?

Solution will come by holding hand of adapter pattern. Let’s create a adapter class to get it done. Within adapter class I will implement client’s demand(Add() function) , And that Add() function will communicate with actual Push() function.

I think it’s clear now.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;

namespace BlogProject
{
    interface IAdaptor
    {
        void Add();
    }

    class Class1 : IAdaptor
    {
        public void Add()
        {
            Console.WriteLine("Iam Class1");
        }
    }

    class Class2
    {
        public void Push()
        {
            Console.WriteLine("I am class2");
        }
    }

    class AdapterClass : IAdaptor
    {
        private Class2 cls = new Class2();
        public void Add()
        {
            cls.Push();
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            AdapterClass C1 = new AdapterClass();
            C1.Add();

            Class1 c = new Class1();
            c.Add();
            Console.ReadLine();
        }
    }

}




No comments:

Post a Comment