I'm reading about the singleton pattern from my ebook (Head First Design Patterns), and I know that using this pattern is suitable in case you need only one instance of some class.
But I have a little trouble with the problem introduction in this ebook.
(Yeah, I think I can quote part of it here !?)
The Chocolate Factory
Everyone knows that all modern chocolate factories have computer controlled chocolate boilers. The job of the boiler is to take in chocolate and milk, bring them to a boil, and then pass them on to the next phase of making chocolate bars.
Here’s the controller class for Choc-O-Holic, Inc.’s industrial strength Chocolate Boiler. Check out the code; you’ll notice they’ve tried to be very careful to ensure that bad things don’t happen, like draining 500 gallons of unboiled mixture, or filling the boiler when it’s already full, or boiling an empty boiler!
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private ChocolateBoiler() {
empty = true;
boiled = false;
}
public void fill() {
if (isEmpty()) {
empty = false;
boiled = false;
// fi ll the boiler with a milk/chocolate mixture
}
}
public void drain() {
if (!isEmpty() && isBoiled()) {
// drain the boiled milk and chocolate
empty = true;
}
}
public void boil() {
if (!isEmpty() && !isBoiled()) {
// bring the contents to a boil
boiled = true;
}
}
public boolean isEmpty() {
return empty;
}
public boolean isBoiled() {
return boiled;
}
}
Yeah, and this is their question:
Choc-O-Holic has done a decent job of ensuring bad things don’t happen, don’t ya think? Then again, you probably suspect that if two ChocolateBoiler instances get loose, some very bad things can happen.
How might things go wrong if more than one instance of ChocolateBoiler is created in an application?
So, the problem will "happen" when we do this:
ChocolateBoiler boiler1 = new ChocolateBoiler(),
boiler2 = new ChocolateBoiler();
//...
But I see that these two instances control its own behavior, and they run independently (because no static field here).
So they run separately without effect to the others.
I wonder that this problem is about illegal state or something might happen when one instance run and effect to the others ("incorrect program behavior, overuse of resources, or inconsistent results", from ebook), but it is not here
So, How might things go wrong here?, is it just about wasteful instance?
Aucun commentaire:
Enregistrer un commentaire