(Creational Design Pattern)
Singleton design pattern is the simplest design pattern we can found. It allows only to create only one instance at a time from the given class.
e.g. clipboard in windows and mobile devices
A singleton class,
- Should be a private class
- provides a global access point to the class (private static)
![]() |
Class diagram |
Implementation
Create a simple java application and create following class
Singleton.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class Singleton { //create global access point private static Singleton firstInstance = null; String clipboard = ""; //keep the constructor private private Singleton(){ } //add synchronized to avoid multiple accesses in multithread environments public static synchronized Singleton getInstance(String text){ if(firstInstance == null){ firstInstance = new Singleton(); //firstInstance.clipboard = text; } firstInstance.clipboard = text; return firstInstance; } } |
SingletonTestDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class SingletonTestDemo { /** * @param args the command line arguments */ public static void main(String[] args) { Singleton instance = Singleton.getInstance("first copy text"); System.out.println("1st instance ID: " + System.identityHashCode(instance)); System.out.println(instance.clipboard + "\n"); Singleton instance2 = Singleton.getInstance("second copy text"); System.out.println("2nd instance ID: " + System.identityHashCode(instance2)); System.out.println(instance2.clipboard + "\n"); } } |
Now test the application
output:
Download source code (GitHub): Click here
No comments:
Post a Comment