Singleton Design Pattern Example
package com.art.head_first.chocolateboiler;
import org.junit.Test;
public class ChocolateBoilerTest {
@Test
public void testChocolateBoiler(){
ChocolateBoiler chocolateBoiler = ChocolateBoiler.getInstance();
chocolateBoiler.fill();
chocolateBoiler.boil();
chocolateBoiler.drain();
}
}
package com.art.head_first.chocolateboiler;
class ChocolateBoiler {
private static ChocolateBoiler uniqueInstance;
private boolean empty;
private boolean boiled;
private ChocolateBoiler() {
empty = true;
boiled = false;
}
/*
Static Singleton Method
By Adding the synchronized keyword to getInstance(), we force every thread to wait its turn
before it can enter the method. That is no two threads may enter the method at the same time.
*/
static synchronized ChocolateBoiler getInstance(){
if (uniqueInstance == null){
uniqueInstance = new ChocolateBoiler();
}
return uniqueInstance;
}
void fill(){
if (empty){
empty = false;
boiled = false;
System.out.println("Filling News Chocolates");
}
}
void boil(){
if (!empty && !boiled){
boiled = true;
System.out.println("Boiling Chocolates");
}
}
void drain(){
if (!empty && boiled){
empty = true;
System.out.println("Draining Chocolates");
}
}
}