JAVA 中单例设计模式之懒汉式和饿汉式

    技术2022-07-16  69

    单例设计模式之懒汉式和饿汉式

    单例设计模式概念 单例模式可以说是大多数开发人员在实际中使用最多的,常见的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 */

    ** 饿汉式** 目的:控制外界创建对象的个数只能创建1个对象 1、 私有化构造方法 2、 在类的内部创建好对象 3、 对外界提供一个公共的get(),返回一个已经准备好的对象

    package cn.tedu.single; //测试单例设计模式 public class Test8_Single { public static void main(String[] args) { Single s = Single.get(); Single s1 = Single.get(); //get()多少次,内存中使用的都是同一个对象 System.out.println(s);//cn.tedu.single.Single@15db9742 System.out.println(s1);//cn.tedu.single.Single@15db9742 } } class Single{ // 1、私有化构造方法,不让外界直接new private Single() {} // 2、在类的内部,创建好对象 //static :静态只能调用静态 static private Single s = new Single(); // 3、对外界提供一个公共的get(),返回一个已经准备好的对象 //static是为了外界不通过对象访问而是通过类名直接方法 static public Single get(){ //注意:静态只能调用静态 return s; } }

    懒汉式

    class Single{ // 1、私有化构造方法,不让外界直接new private Single() {} // 2、在类的内部,创建好对象 //static :静态只能调用静态 static private Single s = null; // 3、对外界提供一个公共的get(),返回一个已经准备好的对象 //static是为了外界不通过对象访问而是通过类名直接方法 synchronized static public Single get(){ //注意:静态只能调用静态 if(s==null){ s = new Single();//会有安全问题 } return s; } }
    Processed: 0.008, SQL: 9