Question

I've just read a fantastic example of a builder pattern.

In my program I'm creating a series of playerCharacter entities, which can be constructed in various ways, with some compulsory fields and some that can be added on as extra or added latter on (after construction). So, after reading the above post, it seems as though I need a builder pattern.

Do I have the option of the builder and super class (here, in the example Pizza and builder) sharing some of the methods? Is there a neat, known solution to this?

For instance if, in the above example (of the pizza), at a later time we had a method of Boolean isPizzaCold() and void heatTo(int degrees) and we wanted the pizza to return false to start with, as it's 'built' hot, and later to let the pizza 'get cold', so that it cools. How would I do this such that they share the same methods?

[edit: as per Joeri's suggestion I've changed the method example.]

Était-ce utile?

La solution

If you take the builder out of the class, it's still a builder. A builder is in the first place a convenient way to construct your object, it doesn't always need to be the only way. You could even state that creating an object is clearly a separate responsibility, and that it is cleaner to separate it (like a factory - builder pattern combined). I personally believe it depends mostly on the complexity of the creation.

No, your object and builder classes cannot share methods. The only way to share method is through inheritance, which clearly is not to be used here.

Your builder is a throwaway object, and the object it constructs is clearly of a different class. The only thing you can do is store the requested value, and call the appropriate setters automatically after the object was built.

void setTemperature(int t){
  this.temperature = t;
}

Pizza build() {
   Pizza pizza = new Pizza(... usual constructor stuff);
   pizza.setTemperature(temperature);
   return pizza;
}

Also, I wonder if void setTemperature(int) makes sense. void heatTo(int degrees) makes more sense to me :)

Autres conseils

I don't really see the relation between your question and the builder pattern. If you want a method setTemperature() and a method isCold(), just add them to the Pizza:

private static final int COLD_THRESHOLD = 40;
private int temperature = 70;

public void setTemperature(int temperature) {
    this.temperature = temperature;
}

public boolean isCold() {
    return temperature <= COLD_THRESHOLD;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top