Design patterns – Adapter

Adapter is a structural pattern. It is used when an existing class is useful, but do not fully implement required interface. This existing class is called adaptee. The required interface is called target. Class which implements target interface and has got reference to adaptee is an adapter.

Imagine we try to write any 2D graphics software. We created an interface IShape2D and already have implemented Triangle class. We need another class – Rectangle. It is already implemented in System.Drawing namespace, but doesn’t fully meet our requirements. We can try to adapt it.

Out interface and Triangle class.

    /// <summary>
    /// Target interface to be implemented by targets.
    /// </summary>
    interface IShape2D
    {
        double CalculateArea();
    }
	
    /// <summary>
    /// Equilateral triangle. 
    /// Out class which implements target interface.
    /// </summary>
    class Triangle : IShape2D
    {
        private int _sideLength;

        public Triangle(int sideLength)
        {
            _sideLength = sideLength;
        }

        public double CalculateArea()
        {
            return Math.Pow(_sideLength, 2) * Math.Sqrt(3) / 4;
        }
    }

Adapted rectangle class.

    /// <summary>
    /// Adapter class.
    /// Contains reference to System.Windows.Rectangle (adaptee) and implements IShape2D interface (target)
    /// </summary>
    class Rectangle : IShape2D
    {
        private System.Drawing.Rectangle _adapteeRectangle;

        public Rectangle(int x, int y, int width, int height)
        {
            _adapteeRectangle = new System.Drawing.Rectangle(x, y, width, height);
        }

        public double CalculateArea()
        {
            return _adapteeRectangle.Width * _adapteeRectangle.Height;
        }
    }
        public static void AdapterUsage()
        {
            var shapes = new List<IShape2D>();
            shapes.Add(new Triangle(4));
            shapes.Add(new Adapter.Rectangle(0, 0, 10, 4));

            foreach (var s in shapes)
            {
                Console.WriteLine(s.CalculateArea());
            }
        }
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