A singleton class can only create a single object — you cannot create more than one object from the class. If you need to use it in multiple places, you reuse the one object.
class CoffeeMachine { private float coffeeQty; private float milkQty; private float waterQty; private float sugarQty;
static private CoffeeMachine instance = null; // static, since it's accessed by the static getInstance() method below
private CoffeeMachine() { // private constructor, so you can't create an object of CoffeeMachine directly coffeeQty = 1; milkQty = 1; waterQty = 1; sugarQty = 1; }
public void fillWater(float qty) { waterQty = qty; } public void fillSugar(float qty) { sugarQty = qty; } public float getCoffee() { return 0.23f; }
static public CoffeeMachine getInstance() { // creates (once) and returns the single instance if (instance == null) { instance = new CoffeeMachine(); } return instance; }}
public class Singleton { public static void main(String[] args) { CoffeeMachine m1 = CoffeeMachine.getInstance(); CoffeeMachine m2 = CoffeeMachine.getInstance(); CoffeeMachine m3 = CoffeeMachine.getInstance();
System.out.println(m1 + " " + m2 + " " + m3); if (m1 == m2 && m1 == m3) { System.out.println("Same"); } }}