简介

某个类只有一个实例,且自行实例化并向整个系统提供此实例

使用场景

在某个系统中,该类只允许创建一个实例对象

代码

  • 饿汉模式
public class HungryModel {

    private final static Student getsingleStudent=new Student();

    public static Student getInstance(){
        return getsingleStudent;
    }

}

  • 懒汉模式
public class LazyModel {

    private  static Student getsingleStudent;

    public static Student getInstance(){
        if (getsingleStudent==null){
            synchronized (LazyModel.class){
                if (getsingleStudent==null){
                    getsingleStudent=new Student();
                }
            }
        }
        return getsingleStudent;
    }
}

Gitee地址

https://gitee.com/zhuayng/foundation-study.git

参考

https://blog.csdn.net/ShuSheng0007/article/details/117266347

相关文章:

  • 2021-11-26
  • 2022-12-23
  • 2021-11-06
  • 2021-10-22
  • 2022-01-21
猜你喜欢
  • 2021-08-28
  • 2021-10-25
  • 2021-09-21
  • 2022-12-23
  • 2021-07-04
  • 2021-09-07
相关资源
相似解决方案