Design patterns in C# – part 6 (Adapter pattern)

Role

The Adapter pattern enables a system to use classes whose interfaces don’t quite match its requirements. It is especially useful for off-the-shelf code, for toolkits, and for libraries.

Design

AdapterPattern

Implementation

  • ITarget -> ISquare
  • Adaptee -> PowerEval
  • Adapter -> Square
  • Client -> TestAdapterPattern
using System;

namespace AdapterPattern
{
    public class TestAdapterPattern
    {
        public static void Main(string[] args)
        {
            var powerEval = new PowerEval();
            Console.WriteLine("Power: 2^4 = {0}", powerEval.Power(2, 4));

            ISquare square = new Square();
            Console.WriteLine("Power: 2^2 = {0}", square.Power(2));
        }
    }

    public interface ISquare
    {
        int Power(int powerBase);
    }

    public class Square : PowerEval, ISquare
    {
        #region ISquare Members

        public int Power(int powerBase)
        {
            return Power(powerBase, 2);
        }

        #endregion
    }

    public class PowerEval
    {
        public int Power(int powerBase, int degree)
        {
            return (int) Math.Pow(powerBase, degree);
        }
    }
}

OUTPUT:

Power: 2^4 = 16
Power: 2^2 = 4

Use when

You have:

  • A domain-specific interface.
  • A class to connect to with a mismatching interface.

You want to:

  • Create a reusable class to cooperate with yet-to-be-built classes.
  • Change the names of methods as called and as implemented.
  • Support different sets of methods for different purposes.

Bibliography

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s