by Michael Thomas
In this tutorial you will be introduced to the "Singleton" design pattern.
Note: On the Design Patterns Home page, you can download this whole tutorial (all content, tutorials & examples) !!!
|
public class
SingletonJVMTraditionalExample { private SingletonJVMTraditionalExample() { } } |
| public
class
SingletonJVMTraditionalExample { private static final SingletonJVMTraditionalExample instance = new SingletonJVMTraditionalExample(); private SingletonJVMTraditionalExample() { } public static SingletonJVMTraditionalExample getInstance() { return instance; } } |
| private SingletonJVMTraditionalExample() {} |
| private static final SingletonJVMTraditionalExample instance = new SingletonJVMTraditionalExample(); |
|
public
static
SingletonJVMTraditionalExample getInstance() { |
|
public void testSingletonTraditionalExample() {
SingletonJVMTraditionalExample object1 =
SingletonJVMTraditionalExample.getInstance(); object2.setName("World"); assertTrue(object1 == object2); assertEquals("World", object1.getName()); assertEquals("World", object2.getName()); } |
|
public enum SingletonJVMEnumExample {INSTANCE; <.... All the original class code comes next! ....> } |
|
private SingletonJVMEnumExample() {} |
|
@Test
SingletonJVMEnumExample object1 =
SingletonJVMEnumExample.INSTANCE; } |
|
private SingletonLazyExample() {} |
| private static SingletonLazyExample instance; |
|
public
static
SingletonLazyExample getInstance() { |
| @Test public void testSingletonLazyExample() { SingletonLazyExample object1 = SingletonLazyExample.getInstance(); object1.setName("Hello"); SingletonLazyExample object2 = SingletonLazyExample.getInstance(); object2.setName("World"); assertTrue(object1 == object2); assertEquals("World", object1.getName()); assertEquals("World", object2.getName()); } |
|
private SingletonLazyInnerClassExample() {} |
|
private
static
class
SingletonHolder { |
|
public
static
SingletonLazyInnerClassExample getInstance() { |
| @Test public void testSingletonInnerClassExample() { SingletonLazyInnerClassExample object1 = SingletonLazyInnerClassExample.getInstance(); object1.setName("Hello"); SingletonLazyInnerClassExample object2 = SingletonLazyInnerClassExample.getInstance(); object2.setName("World"); assertTrue(object1 == object2); assertEquals("World", object1.getName()); assertEquals("World", object2.getName()); } |