Monday, June 23, 2014

The Adapter Pattern in C#

If you need to ever get a class to conform to another interface to provide uniform or predictable functionality, chances are that you will need to use the Adapter Design Pattern.

You can basically think of "real world" adapters such as the AC/DC Power Adapters that you will find with a wide variety of electronic devices or the adapters that you need for power outlets when you travel internationally.

The formal definition of the Adapter Pattern is the following:

The Adapter Pattern converts the interface of a class into another interface the clients expect.  Adapter lets classes work together that couldn't otherwise because of incompatible interfaces (Head First Design Patterns-the adapter pattern)

Since the Head First Design Patterns deals with sample code in Java, I have provided a C# implementation for you instead:

void Main()
{
    MallardDuck duck = new MallardDuck();
 
            WildTurkey turkey = new WildTurkey();
            Duck turkeyAdapter = new TurkeyAdapter(turkey);
 
            Console.WriteLine("The Turkey says....");
            turkey.gobble();
            turkey.fly();
 
            Console.WriteLine("\nThe Duck says....");
            testDuck(duck);
 
            Console.WriteLine("\nThe TurkeyAdapter says...");
            testDuck(turkeyAdapter);
 
}
 
static void testDuck(Duck duck)
        {
            duck.quack();
            duck.fly();
        }
        
public interface Duck
    {
        void quack();
        void fly();
    }
    
  public class MallardDuck : Duck
    {
        public void quack()
        {
            Console.WriteLine("Quack");
        }
 
        public void fly()
        {
            Console.WriteLine("I'm flying");
        }
    }
    
    public interface Turkey
    {
        void gobble();
        void fly();
    }
    
     public class WildTurkey : Turkey
    {
        public void gobble()
        {
            Console.WriteLine("Gobble gobble");
        }
 
        public void fly()
        {
            Console.WriteLine("I'm flying a short distance");
        }
    }
    
     public class TurkeyAdapter: Duck
    {
        private Turkey turkey;
 
        public TurkeyAdapter(Turkey turkey)
        {
            this.turkey = turkey;
        }
        public void quack()
        {
            turkey.gobble();
        }
 
        public void fly()
        {
            for (int i = 0; i < 5; i++)
            {
                turkey.fly();
            }//for
        }
    }

No comments:

Post a Comment