Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Visitor Pattern

Part of TutorialDesignPatterns

Description

Examples of implementing the Gang of Four Visitor Pattern. You can find description on: http://en.wikipedia.org/wiki/Visitor_pattern

Example : Visitor Pattern

import std.stdio;

interface Visitor {
    void visit(Wheel wheel);
    void visit(Engine engine);
    void visit(CarBody carbody);
    void visit(Car car);
}

interface Visitable {
    void accept(Visitor visitor);
}

class Wheel : Visitable {
    char[] name;
    this(char[] name) {
        this.name = name;
    }
    void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class Engine : Visitable {
    void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class CarBody : Visitable {
    void accept(Visitor visitor) {
        visitor.visit(this);
    }
}

class Car : Visitable {
    this() {
        engine = new Engine;
        carbody = new CarBody;
        wheels = [new Wheel("front left"), new Wheel("front right"),
            new Wheel("back left") , new Wheel("back right")];
    }
    void accept(Visitor visitor) {
        visitor.visit(this);
        engine.accept(visitor);
        carbody.accept(visitor);
        foreach(wheel; wheels) {
            wheel.accept(visitor);
        }
    }

    Engine engine;
    CarBody carbody;
    Wheel[] wheels;
}

class PrintVisitor : Visitor {
    void visit(Wheel wheel) {
        writefln("Visiting " ~ wheel.name ~ " wheel");
    }
    void visit(Engine engine) {
        writefln("Visiting engine");
    }
    void visit(CarBody carbody) {
        writefln("Visiting body");
    }
    void visit(Car car) {
        writefln("Visiting car");
    }
}

void main(char[][] args){
    Car car = new Car();
    Visitor visitor = new PrintVisitor();
    car.accept(visitor);
}