Showing posts with label Visitor pattern. Show all posts
Showing posts with label Visitor pattern. Show all posts

Tuesday, 22 May 2012

Visiting the visitor pattern

A colleague of mine showed me the following result.


----------------------------------------------------------------
Current Drawing
----------------------------------------------------------------
Rectangle (10,10) width=30 height=40
Square (15,30) size=35
Ellipse (100,150) diameterH = 300 diameterV = 200
Circle (1,1) size=300
Textbox (5,5) width=200 height=100 Text="sample text"


He asked me whether I can write a simple console application to achieve the above result. Simple task you might say.

Well.. it is pretty obvious that we need to start off with an abstract "Shape" class. But what about the logic to "draw" the shape on the canvas. What we need is an interface like "ICanDraw", which contains the "draw" method. Now, the Shapes can be drawn, therefore the Shape should implement the "ICanDraw" interface. But hang on, each Shape should present itself to the canvas. The canvas should then decide how to "draw" the shape on the canvas.

The most interesting piece here is the text box.  A text box is not strictly a shape, but a "Rectangle" with a additional text property. We can say that a text box is composed of a Rectangle. Internally the text box will use the Rectangle to represent itself.

See the following UML.



My "ICanDraw" interface looks like below.


    /// <summary>
    /// This interface indicates that the shape can be drawn.
    /// </summary>
    public interface ICanDraw
    {
        void Draw(ICanvas canvas);
    }


The abstract "Shape" class looks like below.


    /// <summary>
    /// This is the base class for a shape.
    /// </summary>
    public abstract class Shape : ICanDraw
    {
        public int X { get; private set; }
 
        public int Y { get; private set; }
 
        protected Shape(int x, int y)
        {
            X = x;
            Y = y;
        }
 
        public abstract void Draw(ICanvas canvas);
    }


Keep a close eye on the abstract "Draw" method. Also notice that the "X" and "Y" are "readonly" properties. This plays nicely to the immutability of objects

The "Circle" class looks like below:


    /// <summary>
    /// This is the concrete implementation of a circle.
    /// </summary>
    public class Circle : Shape
    {
        public int Size { get; private set; }
 
        public Circle(int x, int y, int size)
            : base(x, y)
        {
            Size = size;
        }
 
        public override void Draw(ICanvas canvas)
        {
            canvas.Draw(this);
        }
    }


The code for the text box looks like below.


    /// <summary>
    /// This is the concrete implementation of a text box.
    /// </summary>
    public class Textbox : ICanDraw 
    {
        public Rectangle Rectangle { get; private set; }
 
        public string Content { get; private set; }
 
        public Textbox(int x, int y, int width, int height, string content)
        {
            Rectangle = new Rectangle(x, y, width, height);
            Content = content;
        }
 
        public void Draw(ICanvas canvas)
        {
            canvas.Draw(this);
        }
    }


Ok, we have all the concrete classes and a special text box.

Next piece of the puzzle is the "ICanvas". Since we are just writing the content to the console, this will be a special console canvas. The canvas is aware of the shapes and will decide how to draw them. The responsibility to draw a shape is now with the canvas.

The following is the special implementation of "ICanvas" for the console.


/// <summary>
    /// This is the "canvas" representing the console.
    /// </summary>
    public class ConsoleCanvas : ICanvas 
    {
        public void Draw(Circle item)
        {
            Console.WriteLine("Circle({0},{1}) Size={2}", item.X, item.Y, item.Size);
        }
 
        public void Draw(Rectangle item)
        {
            Console.WriteLine("Rectangle({0},{1}) Width={2}, Height={3}", item.X, item.Y, item.Width, item.Height);
        }
 
        public void Draw(Square item)
        {
            Console.WriteLine("Square({0},{1}) Size={2}", item.X, item.Y, item.Size);
        }
 
        public void Draw(Ellipse item)
        {
            Console.WriteLine("Ellipse({0},{1}) DiameterH={2}, Diameter={3}", item.X, item.Y, item.DiameterH, item.DiameterV);
        }
 
        public void Draw(Textbox item)
        {
            Console.WriteLine("TextBox({0},{1}) Width={2}, Height={3}, Text={4}", item.Rectangle.X, item.Rectangle.Y, item.Rectangle.Width, item.Rectangle.Height, item.Content);
        }
    }


As you can see the canvas is aware of the shapes and it decides how to draw them. The canvas will determine this by the runtime type of the object.

Can you see a pattern here? This is in fact the "Visitor" pattern. The purpose of the visitor pattern is to choose a functionality depending on the run-time type of an object. The pattern is also used to introduce additional functionality to an object.

So how do we "draw" these shapes. See below.


        private static void Load()
        {
            var items = new List<ICanDraw>()
                            {
                                new Rectangle(10, 10, 30, 40),
                                new Square(15, 30, 35),
                                new Ellipse(100, 150, 300, 200),
                                new Circle(1, 1, 300),
                                new Textbox(5, 5, 200, 100, "Sample Text")
                            };
 
            items.ForEach(item => item.Draw(new ConsoleCanvas()));
        }

The special "ConsoleCanvas" visits each shape and "draws" it on the console.

In terms of SOLID principals, the "Shape" class is open for extensions and closed for modifications . Yes, the Open/Close principal.

But can the same functionality be achieved through another pattern?

Sunday, 15 April 2012

Visitor Pattern : Revisited

Some developers find design patterns an "Advance" topic. But the reality is that we use design pattern every day and mostly without even knowing.

I find design patterns as an essential element in everyday development. I agree that reading the "Design Patterns" by the Gang of Four (GOF) can be challenging. But trust me, its worth the effort. Although I have not read this book cover to cover, it is an essential reference that you should have access to.

The intent of Visitor pattern according to GOF is "Represent an operation to be performed on elements of an object structure. Visitor lets you to define a new operation without changing the classes of the elements on which it operates.". I think for a developer, the second sentence is the most important piece "without changing the classes".

Consider an example where two tax rate applied to people based on their earnings. The idea here is to  create a "Visitor" to calculate the tax.

[Lets have a quick look at the UML. - Created using Creately]

















Lets start with the "Person" class. This is an abstract class.


    /// <summary>
    /// This is the base class for people.
    /// </summary>
    public abstract class Person
    {
        public string Name { get; private set; }
 
        protected Person(string name)
        {
            Name = name;
        }
 
        /// <summary>
        /// Accept a visitor so that new functionality can be added to the <see cref="Person"/>.
        /// </summary>
        public abstract void Accept(IVisitor visitor);
    }


The above immutable class has a method called "Accept". This is where we "inject" the visitor. The "Person" class is ready to entertain a "Visitor".

The next step is to create the two types of people. In this example they are high and low earners.


    /// <summary>
    /// This is a concrete class of a <see cref="Person"/>.
    /// </summary>
    public class HighEarningPerson : Person
    {
        public decimal Salary { get; private set; }
 
        public decimal Rate { get; private set; }
 
        public HighEarningPerson(string name, decimal salary, decimal rate)
            : base(name)
        {
            Salary = salary;
            Rate = rate;
        }
 
        /// <summary>
        /// The Visitor to this object works on the <see cref="HighEarningPerson"/> instance.
        /// </summary>
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }


This is followed by the low earning person.


/// <summary>
    /// This is a concrete class of a <see cref="Person"/>.
    /// </summary>
    public class LowEarningPerson : Person
    {
        public decimal Salary { get; private set; }
 
        public decimal Rate { get; private set; }
 
        public LowEarningPerson(string name, decimal salary, decimal rate)
            : base(name)
        {
            Salary = salary;
            Rate = rate;
        }
 
        /// <summary>
        /// The Visitor works on the instance of <see cref="LowEarningPerson"/>.
        /// </summary>
        /// <param name="visitor"></param>
        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }
    }


Both classes looks similar, but take a closer look at the "Accept" method. The "Accept" method receives the "Visitor" and calls the "Visit" method passing in the current object. The "Visitor" is now aware of the type of person it is dealing with.

The following is the interface of the "IVisitor".


    /// <summary>
    /// This is the interface of the Visitor that 
    /// works on the concrete types of people. 
    /// </summary>
    public interface IVisitor
    {
        void Visit(HighEarningPerson highEarningPerson);
 
        void Visit(LowEarningPerson lowEarningPerson);
    }


The "IVisitor" works with the concrete "Person" types. So in this case "HighEarningPerson" and "LowEarningPerson". You can see that "IVisitor" is using the method overloading.

Lets look at the implementation of the "IVisitor".


    /// <summary>
    /// This is the Visitor that calculates the tax for each person.
    /// </summary>
    public class TaxVisitor : IVisitor
    {
        private readonly ITaxCalculatorFactory _taxCalculatorFactory;
 
        public TaxVisitor(ITaxCalculatorFactory taxCalculatorFactory)
        {
            _taxCalculatorFactory = taxCalculatorFactory;
        }
 
        public void Visit(HighEarningPerson highEarningPerson)
        {
            var taxCalculator = _taxCalculatorFactory.Create(TaxType.High);
            var tax = taxCalculator.Calculate(highEarningPerson.Salary, highEarningPerson.Rate);
 
            Console.WriteLine("The tax for '{0} - HIGH' is £{1:00}", highEarningPerson.Name, tax);
        }
 
        public void Visit(LowEarningPerson lowEarningPerson)
        {
            var taxCalculator = _taxCalculatorFactory.Create(TaxType.Low);
            var tax = taxCalculator.Calculate(lowEarningPerson.Salary, lowEarningPerson.Rate);
 
            Console.WriteLine("The tax for '{0} - LOW' is £{1:00}", lowEarningPerson.Name, tax);
        }
    }


Do not pay too much attention to the "ITaxCalculatorFactory" that is used here. The reason for using the "ITaxCalculatorFactory" is to keep the creation of the objects out from business processes. Always keep in a note of the Inversion of Control (IoC).

The "TaxVisitor" calculates the tax rate of each person and displays the result.

Lets see how all of this fits in..

I have created a "Console" application. See the following class.


public class VisitorPattern : ITest
    {
        public void Execute()
        {
            Console.WriteLine("**** VISITOR Pattern *****");
            var lowTaxRate = 0.023M;
            var highTaxRate = 0.04M;
 
            var people = new List<Person>()
                             {
                                 new LowEarningPerson("Bob", 23000, lowTaxRate),
                                 new HighEarningPerson("Alice", 45000, highTaxRate),
                                 new LowEarningPerson("Peter", 13000, lowTaxRate),
                                 new HighEarningPerson("Pan", 100000, highTaxRate)
                             };
 
            var taxCalculatorFactory = new TaxCalculatorFactory();
            var taxVisitor = new TaxVisitor(taxCalculatorFactory);
 
            people.ForEach(person => person.Accept(taxVisitor));
        }
    }


We have a collection of "Person" objects. Each has its own type (Low and High earnings). The "TaxVisitor" visits each object and calculates the tax. The output looks like below.


We can clearly see that correct calculate method in the "TaxVisitor" is been called based on the type of the object.

The Visitor pattern is uses the "double-dispatch" to resolve a method call. Double-dispatch simply means the ability to choose the correct method at run-time. So in the above case, although we iterate over a collection of "Person" objects, the run-time type has been used to pick the correct method in the visitor.

Hope you will find this note useful.