黑马程序员技术交流社区
标题:
单例设计模式
[打印本页]
作者:
wyy666
时间:
2014-6-4 21:29
标题:
单例设计模式
class SingleDemo
{
public static void main(String[] args)
{
Student s1 = Student.getstudent();
Student s2 = Student.getstudent();
s1.setAge(30);
s2.setAge(20);
System.out.println(s1.getAge());
}
}
class Student
{
private int age;
private Student(){}
private static Student s = new Student();
/*
private static Student s = new Student()
这句话有个小疑问, 为什么不直接将它修饰为public
然后直接调用s对象,也能起到对象只能建立一个的效果
为什么还要弄getstudent()方法间接调用,
难道有什么隐患吗
*/
public static Student getstudent()
{
return s;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
}
[color=rgb(177, 8, 0) !important]
复制代码
单例设计模式:解决一个类在内存只存在一个对象。
想要保证对象唯一。
1.为了避免其他程序过多建立该类对象,先禁止其他程序建立该类对象
2.还为了让其他程序可以访问到该类对象,只好在本类中,自定义一个对象。
3.为了方便其他程序对自定义对象的访问,可以对外提供一些访问方式。
这三步怎么用代码体现呢?
1.将构造函数私有化。
2.在类中创建一个本类对象。
3.提供一个方法可以获取到该类。
对于事物该怎么描述,还怎么描述。
当需要将该事物的对象保证在内存中唯一时,就将以上的三步加上即可。
作者:
毅心缘
时间:
2014-6-4 23:04
本帖最后由 毅心缘 于 2014-6-4 23:20 编辑
你的代码格式好乱啊
作者:
毅心缘
时间:
2014-6-4 23:07
本帖最后由 毅心缘 于 2014-6-4 23:20 编辑
既然要保证单利,必须要构造函数私有化。只有私有化了,才能保证 不能在其他类中直接new 。
作者:
superob123
时间:
2014-6-4 23:32
没错是可以直接用Student.s来访问,但不安全,哥给你来个Student.s=null你就没地方哭
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2