简介
某个类只有一个实例,且自行实例化并向整个系统提供此实例
使用场景
在某个系统中,该类只允许创建一个实例对象
代码
- 饿汉模式
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