【Java笔记】14 单例设计模式

一、什么是单例设计模式

  1. 采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法
  2. 两种方式:饿汉式和懒汉式

二、饿汉式

类加载时创建,不存在线程安全问题

  1. 构造器私有化,防止直接new
  2. 类的内部创建对象 static
  3. 向外暴露一个静态的公共方法

饿汉式可能造成创建了对象但是没有使用

  1. public class SingleTon01 {
  2. public static void main(String[] args) {
  3. A a = A.getInstance(); //通过方法获取对象
  4. }
  5. }
  6. class A{
  7. private String name;
  8. // 2. 在类的内部直接创建,此时外部不可用
  9. private static A a = new A("aaa");
  10. // 保证只能创建一个对象
  11. // 1. 将构造器私有化
  12. private A(String name){
  13. this.name = name;
  14. }
  15. // 3. 提供一个公共的static方法,返回对象
  16. // 设为静态才能保证不创建对象能直接调用这个方法,因此2中的对象是static的
  17. public static A getInstance(){
  18. return a;
  19. }
  20. }

三、懒汉式

懒汉式只有当用户使用getInstance()时,才能返回对象,再次调用时,会返回上次创建的cat对象,存在线程安全问题

  1. public class SingleTon02 {
  2. public static void main(String[] args) {
  3. Cat instance = Cat.getInstance();
  4. }
  5. }
  6. // 希望在程序运行过程中,只能创建一个Cat对象
  7. class Cat{
  8. private String name;
  9. // 2.定义一个static静态属性对象
  10. private static Cat cat;
  11. // 1. 构造器私有化
  12. private Cat(String name){
  13. this.name = name;
  14. }
  15. // 3. 提供一个public的static方法,可以返回一个Cat对象
  16. public static Cat getInstance() {
  17. if(cat == null) {
  18. cat = new Cat("aaa");
  19. }
  20. return cat;
  21. }
  22. }

四、实例

Runtime工具类的源码

  1. public class Runtime {
  2. private static Runtime currentRuntime = new Runtime();
  3. /**
  4. * Returns the runtime object associated with the current Java application.
  5. * Most of the methods of class <code>Runtime</code> are instance
  6. * methods and must be invoked with respect to the current runtime object.
  7. *
  8. * @return the <code>Runtime</code> object associated with the current
  9. * Java application.
  10. */
  11. public static Runtime getRuntime() {
  12. return currentRuntime;
  13. }
  14. /** Don't let anyone else instantiate this class */
  15. private Runtime() {}