单例模式

单例模式

1.饿汉式
package org.best.singleton;

/**
 * 饿汉式(一进来就创建对象)
 */
public class HungerSingleton {

    private HungerSingleton(){}

    private static HungerSingleton hungerSingleton=new HungerSingleton();

    public static HungerSingleton getHungerSingleton(){
        return hungerSingleton;
    }
}

2.懒汉式
package org.best.singleton;

/**
 * 懒汉式(需要时在创建)
 */
public class LazySingleton {
    //判断是否第一次创建,防止反射
    private static boolean isFirst=true;

    private LazySingleton(){
        synchronized (LazySingleton.class){
          if (isFirst){
              isFirst=false;
          }else {
              throw new RuntimeException("不可重复创建");
          }
        }
    }

    //volatile保证数据原子性
    private static volatile LazySingleton lazySingleton=null;

    public LazySingleton getLazySingleton(){
        /**
         * 当多线程并发操作时,首先判断实例是否为空
         * 当实例为空时,加锁
         * 加锁后,在判断是否为空,为空则赋值
         */
        if (lazySingleton==null){
            synchronized (LazySingleton.class){
                if (lazySingleton==null){
                    lazySingleton=new LazySingleton();
                }
            }
        }
        return lazySingleton;
    }
}

3.静态内部类
package org.best.singleton;

import java.util.PrimitiveIterator;

public class InnerStaticSingleton {

    private InnerStaticSingleton(){}

    public static class getInnerStaticSingleton{
        private static final InnerStaticSingleton SINGLETON=new InnerStaticSingleton();
    }

    private static InnerStaticSingleton getInstance(){
        return getInnerStaticSingleton.SINGLETON;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值