Saturday, November 13, 2010

..........Visitor Pattern

If a Collection contains different classes objects. And we have to iterate the collection than we have to typecast each object to its proper type means we have to use if-else ladder. The best solution for this problem is used Visitor Pattern. Implements all classes with a common interface and again when you will iterate the collection you have to typecast only once in interface type.


The visitor pattern is used when:

* Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure).


Visitor lets you define a new operation without changing the classes of the elements on which it operates.

If you have a collection of objects and you have to perform some action for each object than you will do like this.

public void PrintObjectsType(Arraylist objArlst)
{
Iterator iterator = arlstCollection.iterator()
while (iterator.hasNext())
{
Object objIterator = iterator.next();

if (objIterator as CMale)
Console.WriteLine(“This is Male”);
else if (objIterator as Female)
Console.WriteLine(“This is Female”);
else
Console.WriteLine(“Other”);
}
}

But that is not a good programming practice to use if and else ladder. We can remove it using Visitor Pattern.

public interface IPerson
{
public void DoAction();
}

public class CMale:IPerosn
{
private void DoAction()
{
Console.WriteLine(“This is Male”);
}
}

public class CFemale:IPerosn
{
private void DoAction()
{
Console.WriteLine(“This is Female”);
}
}

public class CPrintPersonType
{
public void PrintPersonType(Arraylist objArlstPerosn)
{
Iterator objIterator = objArlstPerosn.iterator()
while (objIterator .hasNext())
{
IPerson objPerson = iterator.next();
objPerson.DoAction();
}
}
}

No comments:

Followers

Link