Design Pattern means that “we had some problem then we found the solution and gave name to this solution” and Visitor design is also one of the solution so we need to find the problem that Visitor patter has solved and how ?
This design pattern comes under Behavioral Category (It tells that how objects are communicating with each other (objects have been created already)).
================================================================
C++ Visitor Design Pattern :
Standard Definition:
This Design pattern state that There are 2 hierarchy, one is for element and other is for visitor. It is used to represent the operation and its unrelated operation. This is used to add new operation without polluting element hierarchy.
In layman language:
It is like visitor that go to someone house and do some work there and come back, technically we want to do some unrelated function, without polluting existing code.
Problem:
Want to do unrelated function (this function can not be part existing class) and also don’t want to disturb existing hierarchy.
Solution:
Add new hierarchy named visitor and create derived class for each function separately, this function cannot be added in existing code because we don’t want to disturb the existing class or class hierarchy, this solution called as “visitor design pattern“.
When we will use visitor design pattern:
- When we want to do some operation but we cannot disturb the existing code.
- when we want to add new function to existing code but this function cannot be added because it is unrelated function we we add then it will violate the “single responsibility principle”.
Advantage:
- Loose coupling (each unrelated function is represented in separate class).
- Flexible (We can add new function at any time without polluting existing code).
Key Points:
- There will be 2 hierarchy (one for element other for visitor).
- In visitor hierarchy, each class represent each functionality.
- If we add new function in visitor then need to add new class in visitor hierarchy.
- Client can not talk to element class directly, Client needs to talk to visitor first then visitor will talk to element.
- Element hierarchy should be stable.
- It separate the algorithm from data structure (visitor represents algorithm and element is used for data).
- There could be cyclic dependency risk.