Visitor Pattern

Amr elshaer
3 min readMar 27, 2021

--

Visitor Design Pattern in C# with Real-Time Example

The Visitor Design Pattern falls under the category of Behavioural Design Pattern i.e. it is used to change the behavior of a class. As part of this article, we are going to discuss the following pointers related to the Visitor Design Pattern in detail.

The Visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures. It is one way to follow the open/closed principle.

The important part I want to add to your mind is

” when the visitor varies, the execution algorithm of the element object can also vary ” let’s go to the real example.

Please have a look at the following image, we have a school and in school, lots of kids are studying. One day the school management has decided to perform a health checkup for all the kids. So, what the school management has done is appoint one child specialist doctor. What the doctor will do is, he will visit the school and check the health of each and every kid. Once he has checked the health of each kid, then he provides the reports to the school management.

another example:

In the same manner, one school bag sales company wants to promote their school bag. So, the company communicates with the school management and decided to give a school to each kid as a gift. So, the company salesman visits the school and gives a school bag to each kid. For better understanding please have a look at the following diagram.

The conclusion for previous examples is when the visitor changes the algorithm of execution is change in two examples.

so we have visitors and a collection of kids and every visitor will make his behavior in the kids like doctor and salesman.

First We have school is the object structure

and school have kids so the kid is an element and we make an interface

called IKid that contains the name and accept visitor

and Kid

and Visitor that is doctor and SalesMan

and salesman

and the last is client

--

--

Amr elshaer
Amr elshaer

Written by Amr elshaer

Software engineer | .Net ,C# ,Angular, Javascript

No responses yet