CS 342 - 4/22/14 Design Patterns - use of a shared vocalubary to ease communication between people Patterns aren't invented they are discovered. Most patterns and principles address issues of change in software. Singleton Design Pattern (Chapter 5 in HFDP) A design in which only a single instance of the object will be created/exist Standard code features of this design pattern public class MySingleton { private static MySingleton instance = null; private int value; private MySingleton() { } public static MySingleton getInstance() { if (instance == null) instance = new MySingleton(); return instance; } // other methods as needed } ---------- // in method1 MySingelton s1 = MySingleton.getInstance(); s1.setValue (5); // in method2 MySingelton s2 = MySingleton.getInstance(); int x = s2.getValue(); Assume method1 and method2 are in different threads and the data collision occurs, then multiple instances of MySingleton could be created So we need to account for this issue Solution 2: Change the static data member of instance to not be set to null, but invoke the constructor public class MySingleton2 { private static MySingleton2 instance = new MySingleton2(); private int value; private MySingleton2() { } public static MySingleton2 getInstance() { return instance; } // other methods as needed } Solution 3: Use the Synchronized keyword to make sure the constructor executes in a thread-safe manner public class MySingleton3 { private volatile static MySingleton3 instance = null; private int value; private MySingleton3() { } public static synchronized MySingleton3 getInstance() { if (instance == null) instance = new MySingleton3(); return instance; } // other methods as needed } Soultion 4: Restrict the use of synchronized to the portion of getInstance() that actually calls the constructor public static MySingleton3 getInstance() { if (instance == null) { synchronized (MySinglton3.class) { if (instance == null) { instance = new MySingleton3(); } } } return instance; }