单例模式

单例模式
Singleton:只允许创建一个该类的对象

什么场合只能创建一个对象?
	KTV音乐播放器
	

		
方式1:
	饿汉式:类加载时创建,线程安全型
		构造方法私有化
		设置静态属性时创建
		提供静态方法得到对象的实例
		加private方式防止外界访问
		加final修饰可以防止更改地址:可以防止以反射方式更改
		
不存在线程安全问题,天生线程安全,类加载时创建(不好,不用的时候也被迫创建,占用一点点资源)
    
class Singleton{
    private static final Singleton instance = new Singleton();
    private Singleton(){};
    public static Singleton getInstance(){
        return instance;
    }
}
//懒汉式
class Singleton{
    private static Singleton instance = null;
    private Singleton(){}
    public synchronized static Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        } 
        
        return instance;
    }
}

// 防不住反射更改地址,如果已经创建的对象上绑定了特有数据。。。危险了
// 使用时再创建
// 懒汉式,用时再创建,天生线程安全
class Singleton{
    private Singleton(){}
    
    private static class Holder{
        static final Singleton instance = new Singleton();
    }
    
    public static Singleton getInstance(){
        return Holder.instance;
    }
}
// 内部类:需要时才加载内部类
原文地址:https://www.cnblogs.com/raising/p/13111443.html