欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Singleton Pattern

程序员文章站 2024-03-20 20:26:58
...

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;
    }
}