Frontend Engineer
Singapore. 22 July 2020 - talk.js July 2020
Hi, My name is Trung 😊
Use case
What's Visitor pattern?
Architecture and Design
Before Visitor pattern
After Visitor pattern
Pros and cons
Code demo
Q&A
In my application, I have a map view that displaying a route which contains:
Each of them will have the behaviors:
Visitor is a behavioral design pattern that allows adding new behaviors to existing class hierarchy without altering any existing code.
You will see it in action very soon.
If you have multiple concrete classes that inherit from the same base class, or implement the same interface. You should consider using visitor pattern. It will save you from dozens of if-else block or switch/case and typecasting.
Using Google Maps for display marker
PointMarker
StartLocationMarker
RealTimeLocationMarker
The CustomMarkerVisitor interface declares a set of visiting methods that correspond to the number of concrete CustomMarker classes.
The signature of a visiting method allows the visitor to identify the exact class of the component that it's dealing with.
For each concrete class, you will have to implement the accept method, because it is defined as an abstract method.
Concrete class may have special methods that don't exist in their base class or interface. The Visitor is still able to use these methods since it's aware of the component's concrete class.
A concrete CustomMarkerVisitor implement several versions of the same algorithm, which can work with all concrete CustomMarker classes. Think about it as a behavior that each concrete CustomMarker need to have such as click, double click, mouse over, mouse out.
For each behavior, we will have a corresponding visitor to handle.
You see how we still can access to markerData variable on the callback of the mouseover despite the addMarkerToMap has been finished executing.
It is JavaScript Closure.
Code demo
1. Not so easy for a junior developer to pick it up.
2. Too many boilerplate, even if you don't want your concrete class to have a specific behavior. You are forced to implement it.
Live demo
Blog post