设计模式(2)单例模式

单例模式

  1. 饿汉式
public class SingletonTest {
private SingletonTest test2 = new SingletonTest();
/**
* 饿汉式:如果系统没有使用,会造成资源浪费
* 如果初始化中,执行代码多,会使启动慢
*/
public SingletonTest getInst() {
return test2;
}
  1. 懒汉式
public class SingletonTest {
private SingletonTest test = null;
/**
* 懒汉式1 多线程时有并发问题
*/
public SingletonTest getInstance() {
if (test == null) {
test = new SingletonTest();
}
return test;
}

/**
* 懒汉式2 有性能开销 不推荐
*/
public synchronized SingletonTest getInstance2() {
if (test == null) {
test = new SingletonTest();
}
return test;
}
  1. 双重检测+同步锁
    双重校验锁模式不加volatile的影响会线程不安全分析

对象的创建分几步,其中有
1 分配内存空间
2 初始化对象
3 设置instance指向内存地址
如果jvm发生指令重排序,顺序变成1 3 2,那么另一个线程可能会得到null

public class SingletonTest {
// 必须加上 volatile
private volatile  SingletonTest test = null;
private SingletonTest() {
}
/**
* 双重检测+同步锁
*/
public SingletonTest getInstance3() {
    if (test == null) {
        synchronized (SingletonTest.class) {
        if (test == null) {
            test = new SingletonTest();
            }
        }}
return test;
}
}
  1. 枚举
public class EnumTest {
private EnumTest(){}

public static EnumTest getInstance(){
	return Singleton.INSTANCE.getInstance();
}

private enum Singleton{
/**/
INSTANCE ;
private EnumTest enumTest ;
// JVM 来保证只会调用一次
Singleton(){
	enumTest = new EnumTest();
}
public EnumTest getInstance(){
	return enumTest;
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值