Last active
September 27, 2025 12:19
-
-
Save serhii-lypko/96981adf19312d4e42351a5e12ae24c5 to your computer and use it in GitHub Desktop.
Visitor pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * We want to be able to define new operations without having to add a new method | |
| * to each class every time. | |
| * | |
| * The Visitor pattern lets you execute an operation over a set of objects with | |
| * different classes by having a visitor object implement several variants of | |
| * the same operation, which correspond to all target classes. | |
| */ | |
| abstract class Figure { | |
| abstract int getArea(); | |
| abstract void accept(Visitor visitor); | |
| } | |
| class Circle extends Figure { | |
| Circle(int radius) { | |
| this.radius = radius; | |
| } | |
| final int radius; | |
| @Override | |
| int getArea() { | |
| return (int) (Math.PI * radius * radius); | |
| } | |
| // set visitor only once | |
| @Override | |
| void accept(Visitor visitor) { | |
| visitor.visitCircle(this); | |
| } | |
| } | |
| class Rect extends Figure { | |
| Rect(int width, int height) { | |
| this.width = width; | |
| this.height = height; | |
| } | |
| final int width; | |
| final int height; | |
| @Override | |
| int getArea() { | |
| return width * height; | |
| } | |
| // set visitor only once | |
| @Override | |
| void accept(Visitor visitor) { | |
| visitor.visitRect(this); | |
| } | |
| } | |
| interface Visitor { | |
| void visitCircle(Circle circle); | |
| void visitRect(Rect rect); | |
| } | |
| class RenderingVisitor implements Visitor { | |
| public void visitCircle(Circle circle) { | |
| // do rendering stuff for circle | |
| } | |
| public void visitRect(Rect rect) { | |
| // do rendering stuff for rect | |
| } | |
| } | |
| class TransformVisitor implements Visitor { | |
| public void visitCircle(Circle circle) { | |
| // do transforming stuff for circle | |
| } | |
| public void visitRect(Rect rect) { | |
| // do transforming stuff for rect | |
| } | |
| } | |
| public class Playground { | |
| public static void playground() { | |
| final Figure circle = new Circle(10); | |
| final Figure rect = new Rect(10, 20); | |
| final RenderingVisitor renderingVisitor = new RenderingVisitor(); | |
| final TransformVisitor transformingVisitor = new TransformVisitor(); | |
| rect.accept(renderingVisitor); | |
| circle.accept(transformingVisitor); | |
| printArea(circle); | |
| } | |
| static void printArea(Figure figure) { | |
| final int area = figure.getArea(); | |
| System.out.println(area); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment