Visitor Design Pattern falls under Behavioral Pattern of Gang of Four (GOF) Design Patterns in .Net. The command pattern is commonly used in the menu systems of many applications such as Editor, IDE, etc. In this article, I would like to share what is visitor pattern and how is it work?
Visitor Design is used to create and perform new operations onto a set of objects without changing the object structure or classes. This pattern enables loose coupling and the addition of new operations without changing the existing structure.
The UML class diagram for the implementation of the Visitor Design Pattern is given below:
The classes, interfaces, and objects in the above UML class diagram are as follows:
This is a class that has access to the data structure objects and can instruct them to accept a Visitor to perform the appropriate operations.
This is a class that holds all the elements which can be used by visitors.
This is an interface that specifies the Accept operation.
These are classes which implement the Element interface and holds the real information.
This is an interface that specifies the Visit operations for concrete visitors.
These are subclasses which implement the Visitor interface.
public class ObjectStructure { public List Elements { get; private set; } public ObjectStructure() { Elements = new List(); } public void Accept(Visitor visitor) { foreach (Element element in Elements) { element.Accept(visitor); } } } public interface Element { void Accept(Visitor visitor); } public class ConcreteElementA : Element { public void Accept(Visitor visitor) { visitor.Visit(this); } public string Name { get; set; } } public class ConcreteElementB : Element { public void Accept(Visitor visitor) { visitor.Visit(this); } public string Title { get; set; } } public interface Visitor { void Visit(ConcreteElementA element); void Visit(ConcreteElementB element); } public class ConcreteVisitorA : Visitor { public void Visit(ConcreteElementA element) { Console.WriteLine("VisitorA visited ElementA : {0}", element.Name); } public void Visit(ConcreteElementB element) { Console.WriteLine("VisitorA visited ElementB : {0}", element.Title); } } public class ConcreteVisitorB : Visitor { public void Visit(ConcreteElementA element) { Console.WriteLine("VisitorB visited ElementA : {0}", element.Name); } public void Visit(ConcreteElementB element) { Console.WriteLine("VisitorB visited ElementB : {0}", element.Title); } }
An object structure has many unrelated operations to perform on it.
An object structure cannot change but you need to perform new operations on it.
The operations need to perform on the concrete classes of an object structure.