黑马程序员技术交流社区

标题: 单类设计模式,面向对象 [打印本页]

作者: 水尛丶    时间: 2015-11-27 21:54
标题: 单类设计模式,面向对象
单例设计模式:解决一个类在内存只存在一个对象
饿汉式:
       Single类一进内存,就已经创建好了对象。
class Single
{
private static Single s = new Single();
private Single(){}
public static Single getInstance()
{
return s;
}
}
懒汉式:对象是方法被调用时,才初始化,也叫做对象的延时加载。成为:懒汉式。Single 类进内存,对象还没有存在,只有调用了getInstance方法时,才建立对象。
class Single  
{
private static Single s = null; private Single(){}
public static Single getInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
s = new Single();
}
}
return s;
}
}



作者: Little_jie    时间: 2015-11-28 08:41
开发中饿汉式用的比较多
作者: hdhunter    时间: 2015-11-28 10:04
学习了。
作者: hdhunter    时间: 2015-11-28 10:14
Little_jie 发表于 2015-11-28 08:41
开发中饿汉式用的比较多

为什么哪里都有你!
作者: paulchoi1    时间: 2015-11-28 10:26
学习了,哈哈哈哈
作者: wyasln    时间: 2015-11-28 10:52
学习了,昨天才看了单例设计模式
作者: 水尛丶    时间: 2015-11-28 21:45
Little_jie 发表于 2015-11-28 08:41
开发中饿汉式用的比较多

对呢,面向对想这需要背好多东西




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2