简单点说,就是一个应用程序中,某个类的实例对象只有一个,你没有办法去new,因为
构造器是被private修饰的,一般通过getInstance()的方法来获取它们的实例。
getInstance()的返回值是一个对象的引用,并不是一个新的实例,所以不要错误的理解
成多个对象。单例模式实现起来也很容易,直接看demo吧.
1. 懒汉写法(线程不安全)
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
2. 懒汉式写法(线程安全)
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3. 饿汉式写法
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
4. 静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
5. 枚举(这种方式是Effective Java作者Josh Bloch 提倡的方式,它不仅能避免多线程同步问
题,而且还能防止反序列化重新创建新的对象)
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
6. 双重校验锁
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
标签:Singleton,singleton,private,class,static,模式,单例,写法,public
From: https://www.cnblogs.com/18sui/p/17118642.html