Singleton Pattern

Singleton mode: Only one instance.

  1. 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;
    }
}
  1. 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;
    }
}
  1. 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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容