- 懒汉式单例
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){};
public static Singleton getInstance() {
if (uniqueInstance==null) {
uniqueInstance=new Singleton();
}
return uniqueInstance;
}
public static void main(String[] args) {
Singleton singleton=Singleton.getInstance();
Singleton singleton1=Singleton.getInstance();
System.out.println(singleton==singleton1);
}
}
2.这种模式在多线程下是不安全的,可以加synchronized关键字
public static synchronized Singleton getInstance() {
if (single == null) {
single = new Singleton();
}
return single;
}
双重机制
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
3.饿汉式单例,天生就线程安全,有final关键字
public class Singleton1 {
private Singleton1() {}
private static final Singleton1 single = new Singleton1();
//静态工厂方法
public static Singleton1 getInstance() {
return single;
}
public static void main(String[] args) {
Singleton1 sin=Singleton1.getInstance();
Singleton1 sin1=Singleton1.getInstance();
System.out.println(sin==sin1);
}
}
参考自http://blog.csdn.net/jason0539/article/details/23297037/