Pattern Builder Multiple Returns

1

I have a class builder that is responsible for returning an object it builds:

public class ObjetoBuilder {

    private Objeto objeto; 

    public ObjetoBuilder() {
        objeto = new Objeto();
    }

    public ObjetoBuilder adicionarId(Long id) {
        if (id != null) objeto.setId(id);
        return this;
    }

    public Objeto constroi() {
        return objeto;
    }
}

Doubt

Is it a good practice to have more than one build method in a builder ? For example:

public class ObjetoBuilder {
    ...
    public Objeto controi() {
        return objeto;
    }

    public List<Objeto> constroiLista(){
        return Arrays.asList(objeto);
    }

    public String constroiJson() {
        return new Gson().toJson(objeto);
    }

    public String controiXml() {
        return new XStream().toXML(objeto);
    }
}
    
asked by anonymous 28.09.2018 / 13:53

1 answer

1

The constroiJson , constroiLista , and constroiXml methods of your ObjetoBuilder class do not build objects of class Objeto , so they are not part of Design Pattern. They could be part of the Objeto class because they only convert the object to String in different formats (or in the list, in the case of constroiLista ).

You can also use a helper class, which deals with the conversion not only of% class objects, but also something genetic for any class (avoiding duplication of code). I particularly like this option.

    
28.09.2018 / 14:44