黑马程序员技术交流社区

标题: 单例设计模式案例 [打印本页]

作者: hero_king    时间: 2016-6-2 22:44
标题: 单例设计模式案例
简单的写了一个学生类一个老师类,一种是饿汉式一种是懒汉式:
  1. <p>public class Student {
  2. // 构造方法私有化,不让外界创建对象
  3. private Student() {
  4. }</p><p> // 创建对象
  5. private static Student s = new Student();</p><p> // 提供公共的访问方法
  6. public static Student getStuden() {
  7.   return s;
  8. }</p><p>}

  9. public class Teacher {
  10. // 构造方法私有化
  11. private Teacher() {
  12. }</p><p> //延迟加载
  13. private static Teacher t = null;
  14. public synchronized static Teacher getTeacher() {
  15.   if (t == null) {
  16.    t = new Teacher();
  17.   }
  18.   return t;
  19. }
  20. }</p><p>public class TestDemo {
  21. public static void main(String[] args) {
  22.   Student s1 = Student.getStuden();
  23.   Student s2 = Student.getStuden();
  24.   Teacher t1 = Teacher.getTeacher();
  25.   Teacher t2 = Teacher.getTeacher();
  26.   System.out.println(s1 == s2);
  27.   System.out.println(t1 == t2);
  28. }
  29. }
  30. </p>
复制代码






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