Visitor Design Pattern: The visitor design pattern is a way of separating some logic from an object structure on which it operates. Basically it allows you to add new operations on existing classes without modifying them, So visitor design pattern is a great way to provide a flexible design.
Note: Visitor pattern has some flaws.
If we add a new class, the visitor class needs a new method. Furthermore, it is indeed likely that a new visiting method will need the definition of a new visitor, as well as a new accept method in every class of the hierarchy, visitor uses dual dispatching.
When to use: when you have a complex structure, i.e, a hierarchy, tree structure or something else that's not simply linear, you can apply the visitor to simplify the complex structure.
Lets understand it by one hierarchy problem example
Here we have a base class Account and other three classes SavingAccount, CurrentAccount and LoanAccount classes which are derived from Account base class.We can implement these classes as below with some more basic function.
// an abstract class and can not be instantiated
Now suppose we want to display each account details, So we will write a new class say DisplayHandler.java and some logic to display each account details as following.
This class is responsible for displaying various informations for a given account.
Here in displayDetails method we can see many if else conditions and if we have more classes...