单例模式

一:什么是单例?

单例保证一个对象在JVM中只能被实例化一次,常见单例模式有:懒汉式、饿汉式。

二:结构图


三:懒汉式

由于懒汉式是需要的时候才会去实例化,所有是线程不安全的

package com.zz.designpattern;

/**
 * 懒汉式
 * 
 * @Title Singleton01
 * @Description
 * @author Zheng.Zeng
 * @date 2018年7月12日 下午3:20:35
 */
public class Singleton01 {

    private static volatile Singleton01 instanse;

    // 私有化 防止其他类利用new来创建对象
    private Singleton01 () {
    }

    public static Singleton01 getInstanse () {
        if (instanse == null) {
            instanse = new Singleton01 ();
        }
        return instanse;
    }

}

四:双重锁定

由于懒汉式会出现线程安全问题,所以我们可以通过synchronized锁或者lock锁来解决线程按钮问题,但是问题来了,上锁之后会影响性能问题怎么办呢? 当然我们可以使用双重锁定来解决性能问题。为什么说双重锁定可以解决性能问题呢? 因为第一个判断是用来减少进入锁的线程数,而第二个判断用来防止多线程重复实例化对象。 这么一说是不是比直接用锁的性能要好呢? 

package com.zz.designpattern;

/**
 * 懒汉式 双重锁定
 * 
 * @Title Singleton03
 * @Description
 * @author Zheng.Zeng
 * @date 2018年7月12日 下午3:25:41
 */
public class Singleton03 {

    private static volatile Singleton03 instanse;

    private Singleton03 () {
    };

    public static Singleton03 getInstanse () {
        if (instanse == null) {
            synchronized (Singleton03.class) {
                if (instanse == null) {
                    instanse = new Singleton03 ();
                }
            }
        }
        return instanse;
    }

}

五:饿汉式

package com.zz.designpattern;

/**
 * 饿汉式
 * 
 * @Title Singleton02
 * @Description
 * @author Zheng.Zeng
 * @date 2018年7月12日 下午3:22:41
 */
public class Singleton02 {
    private static Singleton02 instanse = new Singleton02 ();

    private Singleton02 () {

    }

    public static Singleton02 getInstanse () {
        return instanse;
    }
}

六:比较实例类

package com.zz.designpattern;

public class Test {

    public static void main (String[] args) {
        // Singleton01 s1 = Singleton01.getInstanse ();
        // Singleton01 s2 = Singleton01.getInstanse ();

        // Singleton02 s1 = Singleton02.getInstanse ();
        // Singleton02 s2 = Singleton02.getInstanse ();
        Singleton03 s1 = Singleton03.getInstanse ();
        Singleton03 s2 = Singleton03.getInstanse ();
        if (s1 == s2) {
            System.out.println ("相同");
        }
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章