lundi 26 octobre 2020

Visitor design pattern for enums

I receive a Response of a given type and value. Based on the type I know how to build the Parameter.

I would like to find a design pattern that allows me to get rid of the line:

if (paramType != reponse.paramType)

I thought to use the Visitor design pattern, but I believe it is not going to work because ParameterType is a enum.

Model:

enum ParameterType {
    NAME, 
    PHOTO;
}

class Response {
    PamarameterType paramType;
    String value;
}

interface IParameter {}
 
class ParameterName implements IParameter {
    static PamarameterType paramType = ParameterType.NAME;
    ParameterName fromReponse(response) {
        if (paramType != reponse.paramType) {
            throw new Exception();
        }
        return parse(response);
    }
    ParameterName parse();
}

class ParameterPhoto implements IParameter  { 
    static PamarameterType paramType = ParameterType.PHOTO;
    ParameterPhoto fromReponse(response) {
        if (paramType != reponse.paramType) {
            throw new Exception();
        }
        return parse(response);
    }
    ParameterPhoto parse();
}   

Service:

ParameterName getParameterName() {
    var response = client.getName();
    var param = ParameterName.fromResponse(response);
    return param;
}

ParameterPhoto getParameterPhoto() {
    var response = client.getPhoto();
    var param = ParameterPhoto.fromResponse(response);
    return param;
}

Aucun commentaire:

Enregistrer un commentaire