11 : 设计模式(单例)

  • 软件设计模式又称为设计模式,是一套被反复利用、经过分类边牧的、代码设计经验的总结
  • 使用设计模式是为了可重用代码,让代码更容易的被人理解,保证代码的可靠性、程序的重用性
  • Java中有23种设计模式,常见的设计模式有:单例设计模式、工厂模式、代理模式、策略模式、委托模式、责任链模式等
单例设计模式
概念

单例模式可以说是大多数开发人员在实际中使用最多的,常见的Spring默认创建的bean就是单例模式的。单例模式有很多好处,比如可节约系统内存空间,控制资源的使用。其中单例模式最重要的是确保对象只有一个。

简单来说,保证一个类在内存中的对象就一个。

RunTime就是典型的单例设计,我们通过对RunTime类的分析,一窥究竟。

源码剖析

/**

 * Every Java application has a single instance of class

 *< code>Runtime</code> that allows the application to interface with

 * the environment in which the application is running. The current

 * runtime can be obtained from the <code>getRuntime</code> method.

 *< p>

 * An application cannot create its own instance of this class.

 *

 * @author  unascribed

 * @see     java.lang.Runtime#getRuntime()

 * @since   JDK1.0

 */

RunTime.java

package java.lang;

 

public class Runtime {

    //1、创建静态的全局唯一的对象

    private static Runtime currentRuntime = new Runtime();

 

    //2、私有构造方法,不让外部来调用

    /** Don't let anyone else instantiate this class */

    private Runtime() {}

 

    //3、通过自定义的静态方法获取实例

    public static Runtime getRuntime() {

        return currentRuntime;

    }

}

分类

 

饿汉式

懒汉式

 

 


 

posted @ 2020-01-12 20:18  aqin1012  阅读(99)  评论(0编辑  收藏  举报