1. 要点:构造函数是私有的,仅本类可创建实例对象
2. 双检锁方式
package com.hj.designPattern.factory.singleton;
public class Singleton {
public static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
// 非线程安全
// if (singleton == null) {
// singleton = new Singleton();
// return singleton;
// }
// return singleton;
// 双检锁方式
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
return new Singleton();
}
}
}
return singleton;
}
}
3. 饿汉方式
package com.hj.designPattern.factory.singleton;
public class SingletonHungary {
// static变量,在类加载时初始化,固线程安全
public static SingletonHungary singletonHungary = new SingletonHungary();
private SingletonHungary() {
}
public static SingletonHungary getInstance(){
return singletonHungary;
}
}



