Visitor in JavaScript
The visitor design pattern concerns itself with being able to add functionality to objects without modifying the structure of them.
With classical inheritance, we often end up with a “base class” that is not used directly; it’s used as an “abstract class,” from which “concrete” classes inherit from our “base class.” For example, with BankAccount
and BankAccountWithInterest
, our class diagram would look as follows, where BankAccountWithInterest
extends BankAccount
and overrides setBalance
.
Figure 3.2: A class diagram for BankAccountWithInterest inheriting from BankAccount
What we can do with the visitor pattern is define BankAccount
, which accepts a visitor and an InterestRateVisitor
visitor class. As a class diagram, it looks as follows. BankAccount
and InterestRateVisitor
are not linked via inheritance; they will be linked at runtime when InterestRateVisitor
is called...