Singleton Design Pattern Tutorial

Singleton Design Pattern TutorialWelcome to my Singleton Design Pattern Tutorial. The Singleton pattern is both easy to understand as well as useful. I’ll demonstrate first how to implement the Singleton pattern. Then I’ll provide and example of its usefulness with a Scrabble example.

Threads can sometimes play havoc with this pattern, so I’ll show you how to avoid those problems. I’ll also review how to use threads, LinkedLists and more.

If you like videos like this, it helps to tell Google

Sharing is nice

If you need to brush up on Java Threads, or Java LinkedLists I have you covered.

Code from the Video

Singleton.java

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;

public class Singleton {
	
	private static Singleton firstInstance = null;
	
	String[] scrabbleLetters = {"a", "a", "a", "a", "a", "a", "a", "a", "a",
			"b", "b", "c", "c", "d", "d", "d", "d", "e", "e", "e", "e", "e", 
			"e", "e", "e", "e", "e", "e", "e", "f", "f", "g", "g", "g", "h", 
			"h", "i", "i", "i", "i", "i", "i", "i", "i", "i", "j", "k", "l", 
			"l", "l", "l", "m", "m", "n", "n", "n", "n", "n", "n", "o", "o", 
			"o", "o", "o", "o", "o", "o", "p", "p", "q", "r", "r", "r", "r", 
			"r", "r", "s", "s", "s", "s", "t", "t", "t", "t", "t", "t", "u", 
			"u", "u", "u", "v", "v", "w", "w", "x", "y", "y", "z",};  
	
	private LinkedList<String> letterList = new LinkedList<String> (Arrays.asList(scrabbleLetters));
   
    // Used to slow down 1st thread
	static boolean firstThread = true;
	
	// Created to keep users from instantiation
	// Only Singleton will be able to instantiate this class
   
	private Singleton() { }
	
	// We could make getInstance a synchronized method to force 
	// every thread to wait its turn. That way only one thread
	// can access a method at a time. This can really slow everything
	// down though
	// public static synchronized Singleton getInstance()
	
	public static Singleton getInstance() {
		if(firstInstance == null) {
			
			// This is here to test what happens if threads try
			// to create instances of this class
			
			if(firstThread){
			
				firstThread = false;
				
				try {
					Thread.currentThread();
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				
					e.printStackTrace();
				}
			}
			
			// Here we just use synchronized when the first object
			// is created
			
			synchronized(Singleton.class){ 
			
				if(firstInstance == null) {
					// If the instance isn't needed it isn't created
					// This is known as lazy instantiation
			
					firstInstance = new Singleton();
			
					// Shuffle the letters in the list
					Collections.shuffle(firstInstance.letterList);
					
				}
			
			}
			
		}
		
		// Under either circumstance this returns the instance
		
		return firstInstance;
	}
	
	public LinkedList<String> getLetterList(){
		
		return firstInstance.letterList;
		
	}
	
	public LinkedList<String> getTiles(int howManyTiles){
		
		// Tiles to be returned to the user
		
		LinkedList<String> tilesToSend = new LinkedList<String>();
		
		// Cycle through the LinkedList while adding the starting
		// Strings to the to be returned LinkedList while deleting
		// them from letterList
		
		for(int i = 0; i <= howManyTiles; i++){
		
			tilesToSend.add(firstInstance.letterList.remove(0));
		
		}
		
		// Return the number of letter tiles requested
		
		return tilesToSend;
		
	}
	
}

ScrabbleTest.java

import java.util.LinkedList;

public class ScrabbleTest {
	
	public static void main(String[] args){
		
		// How you create a new instance of Singleton
		
		Singleton newInstance = Singleton.getInstance();
		
		// Get unique id for instance object
		
		System.out.println("1st Instance ID: " + System.identityHashCode(newInstance));
		
		// Get all of the letters stored in the List
		
		System.out.println(newInstance.getLetterList());
		
		LinkedList<String> playerOneTiles = newInstance.getTiles(7);
		
		System.out.println("Player 1: " + playerOneTiles);
		
		System.out.println(newInstance.getLetterList());
		
		// Try to make another instance of Singleton
		// This doesn't work because the constructor is private
		
		// Singleton instanceTwo = new Singleton();
		
		// Try getting a new instance using getInstance
		
		Singleton instanceTwo = Singleton.getInstance();
		
		// Get unique id for the new instance object
		
		System.out.println("2nd Instance ID: " + System.identityHashCode(instanceTwo));
		
		// This returns the value of the first instance created
		
		System.out.println(instanceTwo.getLetterList());
		
		// Player 2 draws 7 tiles
		
		LinkedList<String> playerTwoTiles = newInstance.getTiles(7);
		
		System.out.println("Player 2: " + playerTwoTiles);
		
	}
	
}

ScrabbleTestThreads.java

public class ScrabbleTestThreads{
	
	public static void main(String[] args){
		
		// Create a new Thread created using the Runnable interface
		// Execute the code in run after 10 seconds
				
		Runnable getTiles = new GetTheTiles();
				
		Runnable getTilesAgain = new GetTheTiles();
				
		// Call for the code in the method run to execute
				
		new Thread(getTiles).start();
		new Thread(getTilesAgain).start();
		
	}
	
}

GetTheTiles.java

import java.util.LinkedList;

public class GetTheTiles implements Runnable {
	
	public void run(){

			// How you create a new instance of Singleton
			
			Singleton newInstance = Singleton.getInstance();
			
			// Get unique id for instance object
			
			System.out.println("1st Instance ID: " + System.identityHashCode(newInstance));
			
			// Get all of the letters stored in the List
			
			System.out.println(newInstance.getLetterList());
			
			LinkedList<String> playerOneTiles = newInstance.getTiles(7);
			
			System.out.println("Player 1: " + playerOneTiles);
		
		System.out.println("Got Tiles");
	}
	
}

36 Responses to “Singleton Design Pattern Tutorial”

  1. Saleh says:

    Nice work Derek,,
    I think that the singleton design pattern can add more elegance to the observer design pattern if used with the subject class, so that only one instance of the subject class created and used by many observers.
    Just an opinion (^-^)

    • admin says:

      Absolutely you can definitely write better code by combining the patterns. I’ll get into combining patterns later along with spotting when you should use them. Many more videos on this topic are coming. Thanks for the input 🙂

  2. Anonymous says:

    like allways. the best.

  3. atul says:

    for making it more thread safe ,it would be better to declare firstThread as volatile in Singleton class :-
    static volatile boolean firstThread = true;

  4. Sekhar says:

    How can i download complete project? Here I didn’t find any link where i can download total project at once… Please let me know… thank you…

  5. Zeyad says:

    Awesome, The best tutorial I have ever came across .You have covered materials that has never been touched by anyone else.your background in the field is SOLID.A+

    Thank you for the time and efforts.

  6. Eric says:

    Derek, What is the difference between this Design Pattern series of video and the OOP design series?
    What is the c++ equivalence of java interface?

    • Derek Banas says:

      The design patterns tutorial just covers common design patterns. The Object Oriented Design tutorial teaches how to think about designing an object oriented program that is easy to understand and manage.

      To create an interface using C++, look into virtual methods. I hope that helps

  7. Zach says:

    Very helpful; tutorials.. Thanks.

  8. Ameya says:

    Just curios – Linkedlist inside the singleton, if made static and singleton class not be made singleton could have achieved the same ?

  9. Arun says:

    Hi Derek,

    There are other ways of breaking Singleton Pattern
    1. Reflection
    2. using Cloneable

    Can you please explain these also?

  10. Ravi K Sharma says:

    Very nice tutorial …I feel this is the best of all what I could found on internet 🙂

  11. Shiva says:

    This is really good with nice explanation.
    But one suggestion , instead of taking that much lengthy code in getInstance() method of Singleton.java to test with threads we can just do with the below code.

    public static Singleton getInstance() {
    if (firstInstance == null) {
    try {
    Thread.currentThread();
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    firstInstance = new Singleton();
    return firstInstance;
    }

    This returns two different instances.

  12. Shiva says:

    private static final Singleton firstInstance = new Singleton();

    I think this gives same instance even for threads also.

  13. Anush says:

    Hi , Thanks for tutorials.

    I think there is a problem in following statement:

    “// Here we just use synchronized when the first object
    // is created
    synchronized(Singleton.class){ ”

    The snippet synchronized(X.class) uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) it is used to make sure that there is exactly one Thread in the block.

    • Anush says:

      sry, my bad, didnt look at the full code 🙁

      Comment gave me an impression that just that line meant tht.

      Thanks anyways

  14. Dan Lovell says:

    Derek, you did a great job with Singleton. I’ve heard others say that you can also use enum and doing so can make for a more simple Singleton effect. What are your thoughts on enum for the purpose of Singleton?

    Many thanks,
    Dan

    • Derek Banas says:

      I think it is a perfectly good solution especially if you know what you’ll need ahead of time.

      • hgala says:

        Hi Derek,

        This is really helpful. I am also watching your android tutorials- they are great too.
        Can you please do a tutorial with trying Singleton with an enum and in general more tutorials on how to break/ test the design patterns.

        Thanks!
        HG

  15. Burak says:

    Hi Derek Thank you very much for these delicious videos,

    I learned a lot of necessary and cool stuff that all programmers or engineer must know.

    You re the best teacher i ‘ ve ever seen on Internet.

    Continue working i will be working with you.

    Cya

  16. Digweed says:

    Hi Derek,

    Good video and examples. I have one feedback. If you can put a copy button for copying code without line letters. It would be great. It is time consuming to delete line numbers. Or you can direcly give link to java source.
    Thanks

  17. Berhanu says:

    what an awesome tutorial. you are a good guy.
    if you can please and an other java product tutorial(j2ee,j2me..
    Any ways thanks

  18. Preethi says:

    Fantastic job on design patterns. Never found any online tutorial so crisp, clean and effective so far. Good job and do please keep going.

Leave a Reply

Your email address will not be published.

Google+