单例简单的说明:
一个类只能有一个实例,该类能自己创建这个实例,并且对外提供获取该实例的接口
单例用在哪?
有时候我们只需要一个类就可以完成所需要的业务了,那么就不需要多次创建对象、管理对象,因为这是一件十分耗费系统资源的事
参考上面简单说明把编写分三步:
public class HungrySingleton {
//构造函数私有化
private HungrySingleton(){}
//内部创建实例
private static HungrySingleton hs = new HungrySingleton();
//获取实例的接口
public static HungrySingleton getInstance(){
return hs;
}
}
public class LazySingleton {
//构造函数私有化
private LazySingleton(){}
//内部先不创建,等到调用接口才创建
private static LazySingleton ls = null;
//获取实例的接口,同步方法,防止多线程访问创建多个对象
public static synchronized LazySingleton getInstance(){
if(ls == null){
ls = new LazySingleton();
}
return ls;
}
}
public class DCL {
//构造函数私有化
private DCL(){}
//可见性
private volatile static DCL dcl = null;
//获取实例的接口
public static DCL getInstance(){
if (dcl == null){
//缩小锁的范围,因为是静态方法,用类锁
synchronized(DCL.class){
if (dcl == null){
dcl = new DCL();
}
}
}
return dcl;
}
}
public class Singleton {
//构造函数私有化
private Singleton (){}
//静态内部类
private static class SingletonHolder {
//final对象不可变
private static final Singleton INSTANCE = new Singleton();
}
//获取对象接口
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
原文:https://www.cnblogs.com/Howlet/p/12016037.html