[ create a new paste ] login | about

Link: http://codepad.org/RPw6Kxu6    [ raw code | fork ]

D, pasted on Apr 28:
import std.stdio: writeln;

interface CarElementVisitor {
    void visit(Wheel wheel);
    void visit(Engine engine);
    void visit(Body thebody);
    void visit(Car car);
}


interface CarElement {
    void accept(CarElementVisitor visitor); // CarElements have to provide accept().
}


class Wheel: CarElement {
    private string name;

    this(string name) {
        this.name = name;
    }

    public string getName() {
        return this.name;
    }

    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}


class Engine: CarElement {
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}


class Body: CarElement {
    public void accept(CarElementVisitor visitor) {
        visitor.visit(this);
    }
}


class Car: CarElement {
    CarElement[] elements;

    this() {
        this.elements = [cast(CarElement)new Wheel("front left"),
                         new Wheel("front right"),
                         new Wheel("back left"),
                         new Wheel("back right"),
                         new Body(),
                         new Engine()];
    }

    public CarElement[] getElements() {
        return elements.dup; // Return a copy of the array of references.
    }

    public void accept(CarElementVisitor visitor) {
        foreach (element; this.getElements())
            element.accept(visitor);
        visitor.visit(this);
    }
}


class CarElementPrintVisitor: CarElementVisitor {
    public void visit(Wheel wheel) {
        writeln("Visiting ", wheel.getName(), " wheel");
    }

    public void visit(Engine engine) {
        writeln("Visiting engine");
    }

    public void visit(Body thebody) {
        writeln("Visiting thebody");
    }

    public void visit(Car car) {
        writeln("Visiting car");
    }
}


class CarElementDoVisitor: CarElementVisitor {
    public void visit(Wheel wheel) {
        writeln("Kicking my ", wheel.getName(), " wheel");
    }

    public void visit(Engine engine) {
        writeln("Starting my engine");
    }

    public void visit(Body thebody) {
        writeln("Moving my thebody");
    }

    public void visit(Car car) {
        writeln("Starting my car");
    }
}


void main() {
    Car car = new Car();
    car.accept(new CarElementPrintVisitor());
    writeln();
    car.accept(new CarElementDoVisitor());
}

/*
Output:
Visiting front left wheel
Visiting front right wheel
Visiting back left wheel
Visiting back right wheel
Visiting thebody
Visiting engine
Visiting car

Kicking my front left wheel
Kicking my front right wheel
Kicking my back left wheel
Kicking my back right wheel
Moving my thebody
Starting my engine
Starting my car
*/


Create a new paste based on this one


Comments: