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();
}
}
}
Saturday, November 13, 2010
Subscribe to:
Post Comments (Atom)
Followers
Link
Labels
Agille
(3)
Angular 2
(96)
Architecture
(7)
ASP .Net
(30)
C#/VB .Net
(161)
Entityframework
(11)
General
(33)
Git
(2)
Hosting
(2)
HTML
(4)
Interview
(12)
Interview-Agile
(1)
Interview-Angular
(25)
Interview-ASP .Net
(3)
Interview-C#
(16)
Interview-JavaScript
(1)
Interview-MVC
(30)
Interview-SQL Server
(4)
Interview-WCF
(2)
Islam
(6)
Java Script
(37)
JQuery
(1)
MVC
(53)
NodeJS
(1)
Puzzles
(1)
React-Native
(3)
Security
(1)
Shayri
(10)
SQL Server
(41)
VC++
(5)
WCF
(21)
Web API
(27)
WPF
(21)
No comments:
Post a Comment