2020-03-16 创建型:单例模式

2020-03-17  本文已影响0人  很菜的花椰菜

饿汉式:

static 1,静态常量 2,静态代码块
在类加载的时候就创建了实例
确实是单例模式,但是造成了内存的浪费,没有实现懒加载 Lazy loading

懒汉式:

3.线程不安全 :使用的时候才创建,只能在单线程情况下使用,而不能在多线程情况下使用
假如一个线程进入了if(singleton == null),还没来得及往下进行,另外一个也进来了,产生多个实例
有潜在的风险,可能破坏了单例模式

4.线程安全,同步方法:
synchronized
但是效率太低了,每一次都要进行同步

5.线程代码块,同步代码块:
synchronized(Singleton.class){
single = new Singleton();
}
问题同线程不安全的模式,假如一个线程进入了if(singleton == null),还没来得及往下进行,另外一个也进来了,产生多个实例
这个方法就是错的

双重检查(推荐!!!!!!)

6.双重检查:
volatile 轻量级,能是修改立即更新到主存
加上
synchronized(){
}
两个if判断

解决线程安全问题,又解决了懒加载的问题,同时保证了效率

7.静态内部类(推荐使用)
class Singleton{

private Singleton(){}

private static class SingletonInstance{

private static final singleton Instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonInstance.Instance;
}

}

当singleton进行类装载的时候,静态内部类是不会被装载的;

当使用 getInstance()时候,静态内部类才会被装载,只会装载一次,而且当JVM类装载的时候,线程是安全的

类的静态属性只会在第一次加载类的时候初始化

8.枚举(推荐使用)

enum 使用枚举,可以实现单例
不仅可以避免多线程同步的问题,而且还可以防止反序列化重新创建新的对象

Java有个类叫 Runtime 就用了单例模式 ,饿汉式

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}
上一篇 下一篇

猜你喜欢

热点阅读