Reputation: 7936
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).
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
Upvotes: 3
Views: 860
Reputation: 1645
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.
Upvotes: 0
Reputation: 49626
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.
Upvotes: 6