一、
1.The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
2.
3.
二、例子一:线程不安全
package headfirst.designpatterns.singleton.chocolate; public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private static ChocolateBoiler uniqueInstance; private ChocolateBoiler() {
empty = true;
boiled = false;
} public static ChocolateBoiler getInstance() {
if (uniqueInstance == null) {
System.out.println("Creating unique instance of Chocolate Boiler");
uniqueInstance = new ChocolateBoiler();
}
System.out.println("Returning instance of Chocolate Boiler");
return uniqueInstance;
} public void fill() {
if (isEmpty()) {
empty = false;
boiled = false;
// fill the boiler with a milk/chocolate mixture
}
} public void drain() {
if (!isEmpty() && isBoiled()) {
// drain the boiled milk and chocolate
empty = true;
}
} public void boil() {
if (!isEmpty() && !isBoiled()) {
// bring the contents to a boil
boiled = true;
}
} public boolean isEmpty() {
return empty;
} public boolean isBoiled() {
return boiled;
}
}
三、加上synchronized
直接在getInstance()方法中加上synchronized虽然线程安全,但得不尝失。因为理想的情况是只在第一次访问getInstance时才需要同步,以后的访问不用同步,因为已经有了instance了
package headfirst.designpatterns.singleton.threadsafe; public class Singleton {
private static Singleton uniqueInstance; // other useful instance variables here private Singleton() {} public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
} // other useful methods here
public String getDescription() {
return "I'm a thread safe Singleton!";
}
}
四、用饿汉式解决线程安全(用static ,JVM会在任何线程访问前初始化变量)
package headfirst.designpatterns.singleton.stat; public class Singleton {
private static Singleton uniqueInstance = new Singleton(); private Singleton() {} public static Singleton getInstance() {
return uniqueInstance;
} // other useful methods here
public String getDescription() {
return "I'm a statically initialized Singleton!";
}
}
Using this approach, we rely on the JVM to create the unique instance of the Singleton when the class is loaded. The JVM guarantees that the instance will be created before any thread accesses the static uniqueInstance variable.
五、用双重检查
package headfirst.designpatterns.singleton.dcl; //
// Danger! This implementation of Singleton not
// guaranteed to work prior to Java 5
// public class Singleton {
private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
With double-checked locking, we first check to see if an instance is created, and if not, THEN we synchronize. This way, we only synchronize the first time through, just what we want.
The volatile keyword ensures that multiple threads handle the uniqueInstance variable correctly when it is being initialized to the Singleton instance.
六、
1.
Q: What about class loaders?
I heard there is a chance that two class loaders could each end up with their own instance of Singleton.A: Yes, that is true as each class loader defines a namespace. If you have two or more classloaders, you can load the same class multiple times (once in each classloader). Now, if that class happens to be a Singleton, then since we have more than one version of the class, we also have more than one instance of the Singleton. So, if you are using multiple classloaders
and Singletons, be careful. One way around this problem is to specify the classloader yourself.
2.
I still don’t totally understand why global variables are worse than a Singleton.
A: In Java, global variables are basically static references to objects.There are a couple of disadvantages to using global variables in this manner. We’ve already mentioned one: the issue of lazy versus eager instantiation. But we need to keep in mind the intent of the pattern: to ensure only one instance of a class exists and to provide global access. A
global variable can provide the latter,but not the former. Global variables also tend to encourage developers
to pollute the namespace with lots of global references to small objects.Singletons don’t encourage this in the same way, but can be abused nonetheless.