IVisitor: Represents the visitor interface with aVisitmethod that operates onIElementobjects.IElement: Represents the element interface with anAcceptmethod that accepts a visitor.
Salesman: Implements theIVisitorinterface. Defines behavior for visiting anIElement(specifically, aKidobject).Doctor: Another implementation ofIVisitor, defining a different behavior for visiting aKid.
Kid: Implements theIElementinterface. Represents an object that can be visited by a visitor.
School: Contains a collection ofIElementobjects (e.g.,Kidinstances) and allows visitors to visit each element.
-
Both
SalesmanandDoctorimplement theVisitmethod from theIVisitorinterface. -
In the
Visitmethod, they check if theIElementpassed is aKidobject using theiskeyword:if (element is Kid kid) { Console.WriteLine($"Salesman: {Name} gave a school bag to the child: {kid.KidName}"); }
-
Salesman: Prints a message about giving a school bag to the child. -
Doctor: Prints a message about performing a health checkup on the child.
- The
Kidclass implements theIElementinterface. - It contains a
KidNameproperty and anAcceptmethod:public void Accept(IVisitor visitor) { visitor.Visit(this); }
- The
Schoolclass contains a collection ofIElementobjects (e.g.,Kidinstances). - It provides a method to allow a visitor to visit all elements in the collection:
public void PerformOperation(IVisitor visitor) { foreach (var element in _elements) { element.Accept(visitor); } }
- A
Schoolobject is created, andKidobjects are added to it. - Visitors (
SalesmanandDoctor) are instantiated and passed to theSchool'sPerformOperationmethod:var school = new School(); school.AddElement(new Kid("John")); school.AddElement(new Kid("Alice")); var salesman = new Salesman("Tom"); var doctor = new Doctor("Dr. Smith"); school.PerformOperation(salesman); school.PerformOperation(doctor);
- A
Schoolobject is created, andKidobjects are added to it. - A
Salesmanand aDoctorare instantiated. - The
PerformOperationmethod ofSchoolis called with each visitor. - Each visitor visits all the
Kidobjects in the school, performing their respective actions.
The Visitor Design Pattern allows adding new operations (e.g., Salesman and Doctor) without modifying the Kid class or other elements. This promotes the Open/Closed Principle, making the code more maintainable and extensible.