关于java:我所知道设计模式之单例模式

前言需要


接下里介绍的是Java 的设计模式之一:单例模式

所谓类的单例设计模式,就是采取肯定的办法保障在整个的软件系统中,对某个类只能存在一个对象实例, 并且该类只提供一个获得其对象实例的办法(静态方法)。

在闻名的Hibernate框架中的SessionFactory,它充当数据存储源的代理,并负责创立 Session 对象。

SessionFactory 并不是轻量级的,个别状况下,一个我的项目通常只须要一个 SessionFactory 就够,这是就会应用到单例模式

一、饿汉式(动态常量)

步骤如下:
1.结构器私有化(避免new)
2.类的外部创建对象
3.对外裸露一个动态的办法

class Singleton {

    //1. 结构器私有化,  内部不能 new
    private Singleton() {}
    
    //2.本类外部创建对象实例
    private final static Singleton instance = new Singleton();

    //3. 提供一个私有的静态方法,返回实例对象
    public static Singleton getInstance() { return instance;}    
}
public static void main(String[] args) {
    //测试
    Singleton instance = Singleton.getInstance();
    Singleton instance2 = Singleton.getInstance(); 
    System.out.println(instance == instance2); // true
    System.out.println("instance.hashCode=" + instance.hashCode()); 
    System.out.println("instance2.hashCode=" + instance2.hashCode());
}

运行后果如下:
true
instance.hashCode=366712642
instance2.hashCode=366712642

优缺点阐明:
1.长处:这种写法比较简单,就是在类装载的时候就实现实例化。防止了线程同步问题。

2.毛病:在类装载的时候就实现实例化,没有达到 Lazy Loading 的成果。如果从始至终从未应用过这个实例,则会造成内存的节约

3.这种形式基于 classloder 机制防止了多线程的同步问题,不过instance 在类装载时就实例化。

在单例模式中大多数都是调用 getInstance 办法,然而导致类装载的起因有很多种

因而不能确定有其余的形式(或者其余的静态方法)导致类装载,这时候初始化 instance 就没有达到 lazy loading 的成果

论断:这种单例模式可用,可能造成内存节约

二.饿汉式(动态代码块)

步骤如下:
1.结构器私有化(避免new)
2.类的外部创建对象
3.对外裸露一个动态的办法

class Singleton {
    
    //1. 结构器私有化,内部不能new
    private Singleton() {}
    
    private static Singleton instance;
    
    //2.在动态代码块中,创立单例对象
    static { 
        instance = new Singleton();
    }
    //3. 提供一个私有的静态方法,返回实例对象
    public static Singleton getInstance() { return instance;}    
}
public static void main(String[] args) {
    //测试
    Singleton instance = Singleton.getInstance();
    Singleton instance2 = Singleton.getInstance(); 
    System.out.println(instance == instance2); // true
    System.out.println("instance.hashCode=" + instance.hashCode()); 
    System.out.println("instance2.hashCode=" + instance2.hashCode());
}

运行后果如下:
true
instance.hashCode=366712642
instance2.hashCode=366712642

优缺点阐明:
1.这种形式和下面的形式其实相似,只不过将类实例化的过程放在了动态代码块中。

也是在类装载的时候,就执行动态代码块中的代码,初始化类的实例。优缺点和下面是一样的

论断:这种单例模式可用,然而可能造成内存节约

三、懒汉式(线程不平安)

步骤如下:
1.结构器私有化(避免new)
2.类的外部创建对象
3.对外裸露一个动态的办法

class Singleton {
    
    //1. 结构器私有化,内部不能new
    private Singleton() {}
    
    private static Singleton instance;
    
    //2. 提供一个私有的静态方法,返回实例对象
    //即提动态的办法,应用到的时候才会创立instance
    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }    
}
public static void main(String[] args) {
    //测试
    Singleton instance = Singleton.getInstance();
    Singleton instance2 = Singleton.getInstance(); 
    System.out.println(instance == instance2); // true
    System.out.println("instance.hashCode=" + instance.hashCode()); 
    System.out.println("instance2.hashCode=" + instance2.hashCode());
}

运行后果如下:
true
instance.hashCode=366712642
instance2.hashCode=366712642

当第一个instance 调用进来时,满足if判断 创建对象

当第二个instance 调用进来时,不满足则间接返回对象

优缺点阐明:

1.起到了 Lazy Loading 的成果,然而只能在单线程下应用

2.如果在多线程下,一个线程进入了 if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句

这时便会产生多个实例。所以在多线程环境下不可应用这种形式

论断:在理论开发中,不要应用这种形式.

四、懒汉式(线程平安,同步办法)

步骤如下:
1.结构器私有化(避免new)
2.类的外部创建对象
3.对外裸露一个动态的办法

class Singleton {
    
    //1. 结构器私有化,内部不能new
    private Singleton() {}
    
    private static Singleton instance;
    
    //2. 提供一个私有的静态方法,返回实例对象
    public static synchronized Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }    
}
public static void main(String[] args) {
    //测试
    Singleton instance = Singleton.getInstance();
    Singleton instance2 = Singleton.getInstance(); 
    System.out.println(instance == instance2); // true
    System.out.println("instance.hashCode=" + instance.hashCode()); 
    System.out.println("instance2.hashCode=" + instance2.hashCode());
}

运行后果如下:
true
instance.hashCode=366712642
instance2.hashCode=366712642

优缺点阐明:

1.解决了线程平安问题
2.效率太低了,每个线程在想取得类的实例时候,执行 getInstance()办法都要进行同步

其实这个办法只执行一次实例化代码就够了,前面的想取得该类实例,间接 return 就行了。办法进行同步效率太低

论断:在理论开发中,不举荐应用这种形式

五、懒汉式(线程平安,同步代码块)

class Singleton {
    
    //1. 结构器私有化,内部不能new
    private Singleton() {}
    
    private static Singleton instance;
    
    //2. 提供一个私有的静态方法,返回实例对象
    public static  Singleton getInstance() {
        if(instance == null) {
            synchronized(Singleton.class){
                instance = new Singleton();
            }
        }
        return instance;
    }    
}

优缺点阐明:
1.这种形式,本意是想对第四种实现形式的改良

因为后面同步办法效率太低,改为同步产生实例化的的代码块。

2.然而这种同步并不能起到线程同步的作用

跟第3种实现形式遇到的情景统一,如果一个线程进入if(singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例

论断:在理论开发中,不要应用这种形式

六、双重查看

class Singleton {
    
    //1. 结构器私有化,内部不能new
    private Singleton() {}
    
    private static volatile Singleton instance;
    
    //提供一个动态的私有办法,退出双重查看代码,解决线程平安问题, 同时解决懒加载问题
    //同时保障了效率, 举荐应用
    public static  Singleton getInstance() {

        if(instance == null) {
            synchronized (Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }   
}

优缺点阐明:

1.Double-Check概念是多线程开发中常应用到的。

如代码中所示,咱们进行了两次 if (singleton == null)查看,这样就能够保障线程平安了。

2.这样,实例化代码只用执行一次,前面再次拜访时,判断 if (singleton == null),间接 return 实例化对象,也防止的重复进行办法同步

3.线程平安、提早加载、效率较高

论断:在理论开发中,举荐应用这种单例设计模式

为什么应用volatile这种形式就举荐呢?请看小编另一篇文章: volatile 的一连串轰炸问题

七、动态外部类

class Singleton {

    //结构器私有化
    private Singleton() {}

    //写一个动态外部类,该类中有一个动态属性 Singleton 
    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    //提供一个动态的私有办法,间接返回 SingletonInstance.INSTANCE
    public static Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

优缺点阐明:

1.这种形式采纳了类装载的机制来保障初始化实例时只有一个线程

2.动态外部类形式在 Singleton 类被装载时并不会立刻实例化,而是在须要实例化时。

调用 getInstance 办法,才会装载 SingletonInstance 类,从而实现 Singleton 的实例化。

3.类的动态属性只会在第一次加载类的时候初始化,所以在这里,JVM 帮忙咱们保障了线程的安全性,在类进行初始化时,别的线程是无奈进入的。

4.长处:防止了线程不平安,利用动态外部类特点实现提早加载,效率高

论断:举荐应用.

八、枚举

enum Singleton {

    INSTANCE; //属性
    public void sayOK() {
        System.out.println("ok~");
    }
}

优缺点阐明:

1.这借助 JDK1.5 中增加的枚举来实现单例模式。不仅能防止多线程同步问题,而且还能避免反序列化从新创立新的对象。

2.这种形式是 Effective Java 作者 Josh Bloch 提倡的形式

论断:举荐应用

九、单例模式源码剖析

其实在咱们 JDK 中,java.lang.Runtime 就是经典的单例模式(饿汉式)

咱们能够一起来剖析看看

public class Runtime {
    //2.类的外部创建对象
    private static Runtime currentRuntime = new Runtime();
    //3.对外裸露一个静态方法
    public static Runtime getRuntime() {
        return currentRuntime;
    }
    //1.结构器私有化
    private Runtime() {}
    
}

十、单例模式的注意事项和细节阐明

一、单例模式保障了 零碎内存中该类只存在一个对象,节俭了系统资源,对于一些须要频繁创立销毁的对象,应用单例模式能够进步零碎性能

二、当想实例化一个单例类的时候,必须要记住应用相应的获取对象的办法,而不是应用 new

三、单例模式应用的场景:

1.须要频繁的进行创立和销毁的对象、创建对象时耗时过多或消耗资源过多(即:重量级对象)

2.常常用到的对象、工具类对象、频繁拜访数据库或文件的对象(比方数据源、session 工厂等)`

参考文献


尚硅谷:设计模式(韩顺平老师):单例模式

Refactoring.Guru:《深刻设计模式》

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理