访客模式的泛化是不可能的?

时间:2016-05-07 11:00:23

标签: java visitor-pattern

有没有办法完全访问访客模式?

我的结论是,如果我想要归一化返回值,那么在JAVA中完全无法访问访客模式是不可能的。只能使访问者/可访问者或ReturnValue成为通用。

示例1 - 返回值是通用的,但访问者/可访问者不是:

public abstract class PaymentType { //Visitable
    public abstract <T> T accept(PaymentTypeVisitor<T> visitor);
}
public interface PaymentTypeVisitor<T> {
    public T visit(CommissionedPaymentType commissionedPaymentType);
    public T visit(SalariedPaymentType salariedPaymentType);
    public T visit(HourlyPaymentType hourlyPaymentType);
}

示例2 - 访客/可访问性是通用的,但返回值不是(不安全的通用):

public interface Visitor<V extends Visitor<V, A>, A extends Visitable<V, A>> {
}
public interface Visitable<V extends Visitor<V, A>, A extends Visitable<V, A>> {
    public abstract <R> R accept(V visitor); //Unsafe generic
}

_

public interface AddEmployeeError extends Error, Visitable<AddEmployeeErrorVisitor, AddEmployeeError> {

}
public interface AddEmployeeErrorVisitor extends Visitor<AddEmployeeErrorVisitor, AddEmployeeError> {
    //Unsafe generics
    <R> R visit(IdAlreadyExistsValidationError idAlreadyExistsValidationError);
    <R> R visit(NameAlreadyExistsValidationError nameAlreadyExistsValidationError);
}

_

public class AddEmployeeUseCaseValidationErrorFormatter implements AddEmployeeErrorVisitor {
    @Override
    protected String format(AddEmployeeError error) {
        return error.accept(this);
    }

    //Unsafe return type
    @Override
    public String visit(IdAlreadyExistsValidationError idAlreadyExistsValidationError) {
        return String.format("%s already owns this id!", idAlreadyExistsValidationError.nameOfExistingUser);
    }

    //Unsafe return type
    @Override
    public String visit(NameAlreadyExistsValidationError nameAlreadyExistsValidationError) {
        return String.format("Name already exists with id: %s", nameAlreadyExistsValidationError.idOfExistingUser);
    }

}

我在这里找到了这个案例:http://musingsofaprogrammingaddict.blogspot.fr/2009/01/visitor-pattern-generic-and-still-type.html

0 个答案:

没有答案