设计模式之单例模式(饿汉,懒汉)

单例模式

单例模式,即single(单一),也就是说整个程序启动后只有这一个实例化对象.也就是static属性.单例模式的应用场景一般是配置文件,比方说日志.

在单例模式中分为懒汉模式和饿汉模式,饿汉顾名思义,很饥渴,在类加载时初始化:public static Xxx xxx = new Xxx();而懒汉则是需要用到的时候再进行初始化,代码如下:

public class ServerConfig {

    public static ServerConfig serverConfig;

    /**
     * 饿汉模式,在类加载时初始化
     * public static ServerConfig serverConfig = new ServerConfig();
     */

    /**
     * 懒汉模式,在使用时初始化
     */
    public static ServerConfig getServerConfig() {
        if (serverConfig == null){
            try {
                //模拟在创建对象前的准备工作,例如读取配置文件之类的操作
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            serverConfig = new ServerConfig();
        }
        
        return serverConfig;
    }

    /**
     * 设定构造方法权限为私有,也就是说只能够通过getServerConfig()方法获得ServerConfig对象
     * @see #getServerConfig()
     */
    private ServerConfig(){

    }
}

多线程环境下的懒汉模式设计

public class ServerConfig{
    private volatile ServerConfig instance = null;
    
    // 构造方法一定要私有, 因为单例模式本身就是只new一次
    // 如果使用其他权限代表别的类也可以创建这个单例对象,不满足单例的定义
    private ServerConfig(){
        
    }

    public static ServerConfig getInstance(){
        // 第一重检查,为了避免使用锁带来的性能消耗
        if (instance == null){
            // 使用类锁确保只有一个线程能够进入实例创建的代码块
            // 注意,可能会有多个线程阻塞在这个位置
            synchronized (ServerConfig.class){
                // 因为可能有多个线程阻塞在上面的位置
                // 第二重检查
                if(instance == null){
                    instance = new ServerConfig();
                }
            }
        }
        return instance;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值