O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Visitor pattern

We have a FamilyMember hierarchy, as shown in the following figure, which is pretty stable. We have another hierarchy, Friends, which is pretty open ended. So now, a FamilyMember needs to accept a Friend.

The Visitor pattern

Figure 7.2: A UML diagram—Visitors

When we have a hierarchy and we need to add a new method to it without modifying it, we use the visitor pattern. Here is the code snippet for this example:

public abstract class FamilyMember { . private String name; public FamilyMember(String name) { this.name = name; } public String getName() { return name; } public abstract void accept(Friend friend); // 1 } public class Husband extends FamilyMember ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required