On se retrouve aujourd'hui pour la solution du précédent #KataOfTheWeek proposé par Gabriel en début de semaine !

public interface CarVisitor {
    void visit(final Engine engine);
    void visit(final Wheel wheel);
    void visit(final Screw screw);

    default void visitCar(final Car car) {
        for (final CarElement carElement : car.getCarElements()) {
            carElement.accept(this);
        }
    }
}

public class PrintElementsVisitor implements CarVisitor {

    private int numberOfScrews;
    private int numberOfEngines;
    private int numberOfWheels;

    @Override
    public void visit(final Engine engine) {
        this.numberOfEngines++;
        engine.getScrews().forEach((s) -> s.accept(this));
    }

    @Override
    public void visit(final Wheel wheel) {
        this.numberOfWheels++;
    }

    @Override
    public void visit(final Screw screw) {
        this.numberOfScrews++;
    }


    public void print() {
        System.out.println("vis: " + numberOfScrews);
        System.out.println("roue: " + numberOfWheels);
        System.out.println("moteur: " + numberOfEngines);
    }
}

public class ComputePriceVisitor implements CarVisitor {

    private double price;
    private int numberOfScrews;

    @Override
    public void visit(final Engine engine) {
        price += (engine.getPower() * 10 + engine.getWeight() * 5);
        engine.getScrews().forEach((s) -> s.accept(this));
    }

    @Override
    public void visit(final Wheel wheel) {
        price += 200;
    }

    @Override
    public void visit(final Screw screw) {
        if(numberOfScrews < 5) {
            price += 0.5;
        }
        numberOfScrews ++;
    }

    public double getPrice() {
        return price;
    }
}

public interface CarElement {
    void accept(CarVisitor carVisitor);
}

// implémentation identique dans Wheel, Engine et Screw
    @Override
    public void accept(final CarVisitor carVisitor) {
        carVisitor.visit(this);
    }

public static void main(final String... args) {
    final Car car = initCar();

    final PrintElementsVisitor printElementsVisitor = new PrintElementsVisitor();
    printElementsVisitor.visitCar(car);
    printElementsVisitor.print();

    final ComputePriceVisitor computePriceVisitor = new ComputePriceVisitor();
    computePriceVisitor.visitCar(car);
    System.out.println("prix: " + computePriceVisitor.getPrice());
}

A bientôt pour un nouveau #KataOfTheWeek !