GOF23设计模式——java五种单例模式

1、饿汉模式

/**
 * 饿汉模式,无延时加载,性能最好
 * 
 * @author Administrator
 *
 */
public class HungrySingleton {

    // 加载类的时候直接创建对象
    private static HungrySingleton instance = new HungrySingleton();

    /**
     * 构造方法要私有
     */
    private HungrySingleton() {
        if (instance != null) {
            throw new RuntimeException("防止反射调用初始化");
        }
    }

    public static HungrySingleton getInstance() {
        return instance;
    }
}

2、懒汉模式

/**
 * 懒汉模式,可以延时加载,但性能差
 * 
 * @author Administrator
 *
 */
public class SlackerSingleton {

    private static SlackerSingleton instance = null;

    /**
     * 构造方法要私有
     */
    private SlackerSingleton() {
        System.out.println("测试懒汉模式");
        if (instance != null) {
            throw new RuntimeException("防止反射调用初始化");
        }
    }

    /**
     * 加上同步synchronized限制
     * @return
     */
    public static synchronized SlackerSingleton getInstance() {
        if (instance == null) {
            instance = new SlackerSingleton();
        }
        return instance;

    }
}

3、双重检测单例模式

/**
 * 双重检测单例模式,性能一般,而且因为JVM的指令重排序可能会导致bug(指令重排序是JVM对语句执行的优化),如果一定要用,则要加上volatile,禁止指令重排序
 * 
 * @author Administrator
 *
 */
public class DoubleCheckSingleton {

    private static volatile DoubleCheckSingleton instance = null;

    /**
     * 构造方法
     */
    private DoubleCheckSingleton() {
        System.out.println("测试双重检测单例模式");
    }

    public static DoubleCheckSingleton getInstance() {
        if (instance == null) {
            synchronized (DoubleCheckSingleton.class) {
                if (instance == null) {
                    instance = new DoubleCheckSingleton();
                }
            }
        }
        return instance;
    }
}

4、静态内部类单例

 /**
  * 静态内部类单例
  * 
  * @author Administrator
  *
  */
public class InnerClassSingleton {

    /**
     * 构造方法,性能
     */
    private InnerClassSingleton() {

    }
    /**
     * 内部类型初始化,可以实现延时加载,当调用getInstance()方法的时候才会初始化内部类,而不是加载的时候就初始化
     * @author Administrator
     *
     */
    public static class InnerClass{
        private static InnerClassSingleton instance = new InnerClassSingleton();
    }

    public static InnerClassSingleton getInstance() {
        return InnerClass.instance;
    }
}

5、枚举单例模式

/**
 * ,枚举单例模式,无延时加载,性能稍微筆餓漢模式差
 * @author Administrator
 *
 */
public enum EnumSingleton {

    // 这里就已经是实力本身
    INSTANCE;

    private EnumSingleton() {
        // 添加直接想做的事情
        init();
    }

    private void init() {
        System.out.println("测试枚举单例模式");
    }

    public void test() {
        System.out.println("test测试枚举单例模式");
    }
}

性能比较

import java.util.concurrent.CountDownLatch;
/**
 * 测试性能
 * 
 * @author Administrator
 *
 */
public class TestPerformance {

    public static void main(String[] args) {
        // 性能: 饿汉模式>静态内部类模式>枚举模式>双重检测模式>懒汉模式
        try {
            testPerformance();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    /**
     * 测试性能
     * 
     * @throws InterruptedException
     */
    private static void testPerformance() throws InterruptedException {
        long time = System.currentTimeMillis();
        int threadNum = 10;
        // CountDownLatch是一个同步工具类,用来协调多个线程之间的同步
        final CountDownLatch countDownLath = new CountDownLatch(threadNum);

        for (int i = 0; i < threadNum; i++) {
            new Thread(new Runnable() {
                //匿名内部类
                @Override
                public void run() {
                    for (int j = 0; j < 100000000; j++) {
                        //HungrySingleton.getInstance();
                        //InnerClassSingleton.getInstance()
                        //EnumSingleton enumSingleton = EnumSingleton.INSTANCE;
                        DoubleCheckSingleton.getInstance();
                        //SlackerSingleton.getInstance();
                    }
                    countDownLath.countDown();
                }
            }).start();
        }
        countDownLath.await();
        // 打印耗时
        System.out.println(System.currentTimeMillis() - time);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值