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

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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.

Jason
Guest

You can create a method accept with the void type return and the two concrete visitors have a state, an example public interface IVisitor { void visit(Employee employee); int getStatus(); } public class VisitPrint implement IVisitor{ public void visit(Employee employee){ //todo } public int getStatus(){ throw new IllegalArgumentException("Not supported operation"); } } public class VisitSum implement IVisitor{ int status; public void visit(Employee employee){ //todo } public int getStatus(){ return status; } } public interface Employee { void accept(Visitor visitor); } This solution resolves the problem and respect the teacher mentality.