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");
	}
	
}

12 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

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Google+