Thursday, May 10, 2012

Design Pattern Study Notes 4 - Singleton













Problem:
only one instance in the system.

Solution:
Singleton pattern

1) singleton class
===================== Singleton.java ====================
package test.pattern.singleton;

public class Singleton {

private static Singleton instance = null;

/*
* the constructor must be private
*/
private Singleton() {
System.out.println("private constructor");
}

/*
* just in case running in multi-thread env,need to add synchronized
*/
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}

return instance;
}
}

2) test class
==================== Client.java ====================
package test.pattern.singleton;

public class Client {

public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1==s2);
}
}

This is the output:
private constructor
true


No comments:

Post a Comment