java单例设计模式

单例设计模式的概念

单例模式可以说是大多数开发人员在实际中使用最多的,常见的Spring默认创建的bean就是单例模式的。
单例模式有很多好处,比如可节约系统内存空间,控制资源的使用。
其中单例模式最重要的是确保对象只有一个。
简单来说,保证一个类在内存中的对象就一个。
RunTime就是典型的单例设计,我们通过对RunTime类的分析,一窥究竟。

源码剖析

/**

  • Every Java application has a single instance of class
    *< code>Runtime 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 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;
}
}

饿汉式

目的:控制外界创建对象的个数只能创建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;
}
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值