设计模式之:单例设计模式

来源:互联网 发布:python实战项目书籍 编辑:程序博客网 时间:2024/05/02 00:00

单例设计模式

单例设计模式概述

单例模式就是要确保类在内存中只有一个对象,该实例必须自动创建,并且对外提供。

优点

在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。

缺点

没有抽象层,因此扩展很难。

职责过重,在一定程序上违背了单一职责

单例模式:

         饿汉式:类一加载就创建对象

         懒汉式:用的时候,才去创建对象

 

例子1:单例设计模式之饿汉式

public classStudent {

   // 构造私有

   private Student() {

   }

 

   // 自己造一个

   // 静态方法只能访问静态成员变量,加静态

   // 为了不让外界直接访问修改这个值,加private

   private static Student s = new Student();

 

   // 提供公共的访问方式

   // 为了保证外界能够直接使用该方法,加静态

   public static Student getStudent() {

      return s;

   }

}

 

/*

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

 *

 * 如何保证类在内存中只有一个对象呢?

 *    A:把构造方法私有

 *    B:在成员位置自己创建一个对象

 *    C:通过一个公共的方法提供访问

 */

public classStudentDemo {

   public static void main(String[] args) {

      // Student s1 = new Student();

      // Student s2 = new Student();

      // System.out.println(s1 == s2); // false

 

      // 通过单例如何得到对象呢?

 

      // Student.s = null;

 

      Students1 = Student.getStudent();

      Students2 = Student.getStudent();

      System.out.println(s1 == s2);

 

      System.out.println(s1);// nullcn.itcast_03.Student@175078b

      System.out.println(s2);// nullcn.itcast_03.Student@175078b

   }

}

运行结果:

true

day24.Student@1a477b7

day24.Student@1a477b7

 

例子2:单例设计模式之懒汉式

/*

*

 * 面试题:单例模式的思想是什么?请写一个代码体现。

 *

 *    开发:饿汉式(是不会出问题的单例模式)

 *    面试:懒汉式(可能会出问题的单例模式)

 *        A:懒加载(延迟加载

 *        B:线程安全问题

 *           a:是否多线程环境

 *           b:是否有共享数据

 *           c:是否有多条语句操作共享数据  

 */

public classTeacher {

   private Teacher() {

   }

 

   private static Teacher t = null;

 

   public synchronized static Teacher getTeacher() {

      if (t ==null) {

         t = new Teacher();

      }

      return t;

   }

}

 

public classTeacherDemo {

   public static void main(String[] args) {

      Teachert1 = Teacher.getTeacher();

      Teachert2 = Teacher.getTeacher();

      System.out.println(t1 == t2);

      System.out.println(t1);// cn.itcast_03.Teacher@175078b

      System.out.println(t2);// cn.itcast_03.Teacher@175078b

   }

}

运行结果:

true

day24.Teacher@afccbe

day24.Teacher@afccbe

0 0
原创粉丝点击