Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Visitor Pattern in Java whit two different return types

I am trying to implement the Visitor Pattern in java (exercise for home, sorry) for an object structure which has methods with different return types (int and void).

A concreteVisitor (i.e., CostAss) returns int and a second ConcreteVisitor (i.e., drawCosts) returns void (i.e., a print of the cost).

enter image description here

I have the problem to understand how to implement this problem. I am not allowed to create two accept methods (one int e one void) in the interface Employee

enter image description here

like image 419
Gianni Spear Avatar asked Feb 17 '26 21:02

Gianni Spear


1 Answers

From a Java perspective, these methods are the same because the return type is not a part of the method signature.

The diagram wasn't intended for Java. However, it's possible to work around it with generics.

interface Employee<T> {
  Optional<T> accept(Visitor visitor);
}

class Assistant implements Employee<Integer> {
  @Override
  public Optional<Integer> accept(Visitor visitor) {
    return Optional.of(100);
  }
}

class Manager implements Employee<Void> {
  @Override
  public Optional<Void> accept(Visitor visitor) {
    return Optional.empty();
  }
}

I am not a huge supporter of this idea, I just wanted to share the way it can be done.

like image 53
Andrew Tobilko Avatar answered Feb 19 '26 10:02

Andrew Tobilko