黑马程序员技术交流社区
标题:
单例设计模式案例
[打印本页]
作者:
hero_king
时间:
2016-6-2 22:44
标题:
单例设计模式案例
简单的写了一个学生类一个老师类,一种是饿汉式一种是懒汉式:
<p>public class Student {
// 构造方法私有化,不让外界创建对象
private Student() {
}</p><p> // 创建对象
private static Student s = new Student();</p><p> // 提供公共的访问方法
public static Student getStuden() {
return s;
}</p><p>}
public class Teacher {
// 构造方法私有化
private Teacher() {
}</p><p> //延迟加载
private static Teacher t = null;
public synchronized static Teacher getTeacher() {
if (t == null) {
t = new Teacher();
}
return t;
}
}</p><p>public class TestDemo {
public static void main(String[] args) {
Student s1 = Student.getStuden();
Student s2 = Student.getStuden();
Teacher t1 = Teacher.getTeacher();
Teacher t2 = Teacher.getTeacher();
System.out.println(s1 == s2);
System.out.println(t1 == t2);
}
}
</p>
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2