黑马程序员技术交流社区

标题: 懒汉式 饿汉式 [打印本页]

作者: 122125241    时间: 2015-7-12 13:16
标题: 懒汉式 饿汉式
  1. 饿汉式
  2. public class Student {
  3.         //为了不让外界创造该类的对象,选择构造私有化
  4.         private Student() {
  5.                 super();
  6.                 // TODO Auto-generated constructor stub
  7.         }
  8.          //自己创建自己的对象
  9.         private static        Student student = new Student();
  10.        
  11.         //用一个方法传出该对象
  12.         public static Student getStudent(){
  13.                
  14.                 return student;
  15.         }
  16. }
  17. 懒汉式(面试一般写这种)
  18. public class Student {
  19.         //为了不让外界创造该类的对象,选择构造私有化
  20.         private Student() {
  21.                 super();
  22.                 // TODO Auto-generated constructor stub
  23.         }
  24.         private static        Student student1 = null;
  25.         public synchronized static Student geStudent1(){
  26.                 if (student1== null) {
  27.                         student1 = new Student();
  28.                 }
  29.                
  30.                 return student1;
  31.         }
  32. }
复制代码







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