Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern - doubt in Head First Design Patterns book

Tags:

oop

singleton

On page 175, there is an example of Chocolate Boiler class. Something like this:

public class ChocolateBoiler {  

  private boolean empty;  
  private boolean boiled;  

  public ChocolateBoiler {  
    empty = true;  
    boiled = false;  
  }  
 // and then three methods to fill, drain and boil which changes the  
 // status of these two flag depending of situation
}  

In section "brain power" they ask a question "How might things go wrong if more than one instance of ChocolateBoiler is created in an application?"

I'm not sure what's the problem with this class. Why do we introduce a singleton pattern here? These two flags are not static and so one per instance. So how creating more than one instance can mess things up?

like image 388
alonzo Avatar asked May 24 '09 11:05

alonzo


People also ask

Is head first design pattern written in Java?

Book description This edition of Head First Design Patterns—now updated for Java 8—shows you the tried-and-true, road-tested patterns used by developers to create functional, elegant, reusable, and flexible software.

Are there more than 23 design patterns?

As per the design pattern reference book Design Patterns - Elements of Reusable Object-Oriented Software , there are 23 design patterns which can be classified in three categories: Creational, Structural and Behavioral patterns.

What is a singleton factory pattern with example?

Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program. The Singleton pattern disables all other means of creating objects of a class except for the special creation method.


2 Answers

The question isn't about making an instance of an object.

It's about the confusion caused by having two instances of the object, both of which purport to have the status of the ChocolateBoiler.

If some Object (for example, Cooker) thinks it has the status of the ChocolateBoiler, and some other Object (for example, Recipe) things it has the status of the ChocolateBoiler, what happens now?

Since the variables are instance variables, the ChocolateBoiler objects won't agree on the status of the ChocolateBoiler. Now what happens?

like image 104
S.Lott Avatar answered Oct 10 '22 03:10

S.Lott


It's only a problem if there only can be one ChocolateBoiler, and if there only can be one, it should be a singleton.

like image 39
ralphtheninja Avatar answered Oct 10 '22 03:10

ralphtheninja