Created
July 15, 2018 22:56
-
-
Save arttuladhar/de679bd2e55575d3be92db5d3e4a402c to your computer and use it in GitHub Desktop.
Singleton Design Pattern Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment