黑马程序员技术交流社区
标题: 单例设计模式的两种方式 [打印本页]
作者: ytooo00 时间: 2015-5-13 21:15
标题: 单例设计模式的两种方式
本帖最后由 ytooo00 于 2015-5-13 21:31 编辑
单例设计模式的两种方式
A:饿汉式 当类加载的时候,就创建对象。
class Student
{
private Student(){}
private static final Student s = new Student();
public static Student getInstance()
{
return s;
}
}
B:懒汉式 当使用的使用,才去创建对象。
class Student
{
private Student(){}
private static Student s = null;
public static Student getInstance()
{
if(s==null)
{
//线程1就进来了,线程2就进来了。
s = new Student();
}
return s;
}
}
作者: yihuihua 时间: 2015-5-13 21:24
private static final Student s = null;
错了,这是终身为空呀
作者: ytooo00 时间: 2015-5-13 21:32
谢谢 已修改
| 欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |