java 23 - 2 设计模式之单例模式

 单例模式:保证类在内存中只有一个对象。

 如何保证类在内存中只有一个对象呢?
   A:把构造方法私有
   B:在成员位置自己创建一个对象
   C:通过一个公共的方法提供访问

 

单例模式之饿汉式:  (一进来就造对象,一回家就吃饭,饿。。)

 

 1 public class Student {
 2     // A:把构造方法私有
 3     private Student() {
 4     }
 5   
 6     // 在成员位置自己创建一个对象
 7     // 静态方法只能访问静态成员变量,加静态
 8     // 为了不让外界直接访问修改这个值,加private
 9     private static Student s = new Student();
10 
11     // C:通过一个公共的方法提供访问
12     // 为了保证外界能够直接使用该方法,加静态
13     public static Student getStudent() {
14         return s;
15     }
16 }

 

测试类:

 1 public class StudentDemo {
 2     public static void main(String[] args) {
 3         //按照平常来创建2个对象试试
 4         // Student s1 = new Student();
 5         // Student s2 = new Student();
 6         // System.out.println(s1 == s2); // false,地址值不一样,证明是2个不同的对象
 7 
 8         
 9         //下面是直接更改了对象s的值,要避免这样的情况,所以在Student类中给对象加私有private
10         //Student.s = null;
11         
12         // 通过单例如何得到对象呢?
13         Student s1 = Student.getStudent();
14         Student s2 = Student.getStudent();
15         System.out.println(s1 == s2);
16 
17         System.out.println(s1); // null,cn.itcast_03.Student@175078b
18         System.out.println(s2);// null,cn.itcast_03.Student@175078b
19     }
20 }

 

单例模式之懒汉式:(用的时候才创建对象,不饿不吃)

 1 public class Teacher {
 2     private Teacher() {
 3     }
 4     //先不创建对象,就是没new
 5     private static Teacher t = null;
 6 
 7     public synchronized static Teacher getTeacher() {
 8         // 为了防止出现线程安全问题,这里使用同步机制:synchronized
 9         //使用的时候,进行判断
10         if (t == null) {
11             //如果是第一次使用,就创建对象
12             t = new Teacher();
13         }
14         //不是第一次,就返回之前创建的对象
15         return t;
16     }
17 }

 

测试类:

1 public class TeacherDemo {
2     public static void main(String[] args) {
3         Teacher t1 = Teacher.getTeacher();//t1进去Teacher中是null,创建对象
4         Teacher t2 = Teacher.getTeacher();//t2进去不是null,用的t1创建的对象
5         System.out.println(t1 == t2);
6         System.out.println(t1); // cn.itcast_03.Teacher@175078b
7         System.out.println(t2);// cn.itcast_03.Teacher@175078b
8     }
9 }

 

 单例模式:
   饿汉式:类一加载就创建对象
   懒汉式:用的时候,才去创建对象

 面试题:单例模式的思想是什么?请写一个代码体现。
   开发:饿汉式(是不会出问题的单例模式)
   面试:懒汉式(可能会出问题的单例模式)
       A:懒加载(延迟加载)
         B:线程安全问题
          a:是否多线程环境 多线程环境下是
          b:是否有共享数据 是,对象t就被共享了
          c:是否有多条语句操作共享数据 是,t1、t2就在共同操作t

 

还有看这个文章,转载:

JAVA设计模式之单例模式

 

posted @ 2016-10-12 11:44  卡拉瓦  阅读(190)  评论(0编辑  收藏  举报