Skip to content

Instantly share code, notes, and snippets.

@georgelesica-wf
Created July 18, 2017 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgelesica-wf/b70fcc49563b56604004e27cc6992f9a to your computer and use it in GitHub Desktop.
Save georgelesica-wf/b70fcc49563b56604004e27cc6992f9a to your computer and use it in GitHub Desktop.
A quick example of the visitor pattern using the Dart programming language.

Visitor Pattern in Dart

A couple nice references on the visitor pattern:

  1. Source Making - Visitor
  2. Crafting Interpreters

The code in this Gist implements a simple visitor using nonsensical, but reasonably clear, types.

We have a set of primitive-alikes upon which we would like to perform various operations. We use a visitor to implement the "biggify" operation.

import 'crazy_primitive.dart';
import 'crazy_visitor.dart';
class BiggifyVisitor extends CrazyVisitor {
@override
void visitInt(CrazyInt element) {
element.value += 100;
}
@override
void visitString(CrazyString element) {
element.value.toUpperCase();
}
}
import 'crazy_visitor.dart';
abstract class CrazyPrimitive<T> {
T value;
void accept(CrazyVisitor visitor);
}
class CrazyDouble extends CrazyPrimitive<double> {
/// This type does nothing upon accepting a visitor.
/// One drawback of the visitor pattern is that it is
/// more difficult to add additional types since every
/// new type requires a new method to be added on the
/// base visitor class, which then potentially
/// requires all concrete visitors to be updated.
@override
void accept(CrazyVisitor visitor) {}
}
class CrazyString extends CrazyPrimitive<String> {
@override
String value;
@override
void accept(CrazyVisitor visitor) {
visitor.visitString(this);
}
}
class CrazyInt extends CrazyPrimitive<int> {
@override
int value;
@override
void accept(CrazyVisitor visitor) {
visitor.visitInt(this);
}
}
import 'crazy_primitives.dart';
abstract class CrazyVisitor {
void visitString(CrazyString element);
void visitInt(CrazyInt element);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment