Singleton Pattern
程序员文章站
2024-03-20 20:26:58
...
Singleton mode: Only one instance.
- Lazy-created singleton, but not Thread-safe.
public class A {
private static A a = null;
// non-args constructor should be private, thus not being called.
private A(){
}
// instantiate it the first time called and never instantiate again.
public static A getInstance(){
if(A == null){ // when more than one threads run here, maybe more than one instances will be created.
a = new A();
}
return a;
}
}
- But if needing Thread-safe, there are 3 ways. All are lazy-created.
// 1. pay attention to synchronized.
public synchronized static A getInstance(){
if(a == null)
a = new A();
return a;
}
//2. double check
// Pay attetion to volatile. viewed to synchronized. You can also choose not to use volatile.
private volatile static A a = null;
public static A getInstance(){
if(a == null){ // check once;
synchronized(A.class){
if(a == null) // check twice;
a = new A();
}
}
return a;
}
//3. lazy-load and thred-safe.
public class A {
private A(){ // gurantee non-args constructor will be created.
}
private static class LazyHolder{ // only instantiate it once when called.
private static final A a = new A();
}
public static A getInstance(){
return LazyHolder.a;
}
}
- The simplest and hungry way. Thread-safe. Instantiate when init class, not lazy-created.
public class A {
private static final A a = new A();
private A(){
}
public static A getInstance(){
return a;
}
}
上一篇: Singleton Pattern
下一篇: 利用js实现网页开关灯