设计模式--单例模式

单例模式,即一个JVM内存中只存在某一个类的唯一实例对象,它具有全局唯一性,可以设置为全局共享的资源,避免操作多个对象模拟共享资源时引起的逻辑冲突。
单例模式不对外声明构造器,需要将构造器私有化防止外部其他类调用,此外还需要对外暴露一个静态属性或静态方法向外部提高自己唯一单例对象。

1.饿汉式单例

饿汉式单例,即很饿,这个类一旦被加载他就需要这个实例,该实例对象在类加载的时候就创建,在多线程环境下也能保证安全。
写法如下:

/**
 * 饿汉式单例
 */
public class HungryMan {
    //构造器私有
    private HungryMan(){
    }
    //供外部调用的属性(若声明为public,则还可以通过HungryMan.hungryMan调用)
    private static final HungryMan hungryMan = new HungryMan();
    //供外部调用的方法
    public static HungryMan getInstance(){
        return hungryMan;
    }
}

class Test{
    public static void main(String[] args) {
        System.out.println(HungryMan.getInstance());
        System.out.println(HungryMan.getInstance());
    }
}

控制台打印出:

com.example.study.DesignPattern.单例模式.饿汉式单例.HungryMan@506e1b77
com.example.study.DesignPattern.单例模式.饿汉式单例.HungryMan@506e1b77

可见两次调用的确实是同一个对象,即饿汉式单例的调用

2.1懒汉式单例

饿汉式单例,即很懒,这个类第一次被引用的时候才去创建单例对象,所以对比饿汉式单例,懒汉式单例应该这么写:

/**
 * 懒汉式单例
 */
public class LazyMan {
    //构造器私有
    private LazyMan(){}
    //LazyMan的单例对象,并不在第一时间就创建
    private static LazyMan lazeMan;
    //供外部调用的方法,返回LazyMan的单例对象
    public static LazyMan getInstance(){
        if (lazeMan == null){
            lazeMan = new LazyMan();
        }
        return lazeMan;
    }
}

仍然输出两条System.out.println(HungryMan.getInstance());发现控制台打印了两条
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@506e1b77
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@506e1b77
确实还是我们预期的结果,但是如果考虑到多线程环境下,创建20个线程,每个线程都去调用getInstance方法,在测试中这样输出:

	public static void main(String[] args) {
        System.out.println("======================");
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                System.out.println(LazyMan.getInstance());
            }).start();
        }
    }

而他的结果为

======================
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@219a0906
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@625eb514
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1

发现前三条数据出现了问题,这是三不同的对象,为了更明显的显示,在构造方法中添一条输出语句,

	private LazyMan(){
        System.out.println("LazyMan的构造方法调用了!");
    }

发现控制台的信息为

======================
LazyMan的构造方法调用了!
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@1f6f243
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@1f6f243
LazyMan的构造方法调用了!
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@332b9c83
LazyMan的构造方法调用了!
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@219a0906
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@332b9c83
LazyMan的构造方法调用了!
LazyMan的构造方法调用了!
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@12b590e1
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@219a0906
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@7d383fb

可见构造方法的确被调用了不止一次,这就有悖于单例模式的设计初衷了,而产生这个问题的原因是多线程的极端环境下:
线程A调用getInstance方法,此时lazeMan == null,于是线程A去堆区创建lazeMan的实例对象,但是创建实例并非瞬间的过程,在A创建的过程中,线程B也来调用getInstance方法,因为该实例对象并未创建完成,此时lazeMan未能指向实力对象,即lazeMan 还是null,线程B又发起了创建对象的请求,这就造成了多线程环境下创建了多个实例对象。

2.2双重检测锁机制

为了避免多线程下创建多个实例,首先需要解决多线程竞争的问题,我们对LazeMan的类对象加锁,在某一个线程调用getInstance方法时,其他线程不能再进行getInstance方法中,需要再外等待线程A释放掉LazeMan的类对象锁,getInstance方法写法如下

	// 1.synchronized 加在方法上
	public synchronized static LazyMan getInstance(){
        if (lazeMan == null){
            lazeMan = new LazyMan();
        }
        return lazeMan;
    }

	// 2.synchronized 代码块
	public static LazyMan getInstance(){
        if (lazeMan == null){
            synchronized(LazyMan.class){
                if (lazeMan == null){
                    lazeMan = new LazyMan();
                }
            }
        }
        return lazeMan;
    }

两种写法的作用一样,1是调用就加锁,执行效率比2低,以2为例,在调用getInstance方法进行2次检查,若lazeMan为null,锁住LazyMan.class对象(而不是lazeMan,每一个类都有一个class对象,存储的是每一个类的类信息),还以线程AB为例,在多线程极端环境下AB都进入到了第一层判断中,A先上锁B等待,A进行对象创建,完成后释放锁,此时B得到锁但是此时lazeMan 已经在堆区有了引用,线程B不能进入第二层if判断中,所以多个线程仍能确保单例唯一性。

3.反射破环单例

反射可以获取类加载器和类的属性和方法等一系列信息,不管是饿汉式单例还是懒汉式单例都有一个共同的特点,即构造器私有,那么我们通过反射获取类的构造器,破环它的私有设置,在调用构造器是不是也能创建出新的实例。

	public static void main(String[] args) throws Exception {
        System.out.println("======================");
        LazyMan instance = LazyMan.getInstance();
        System.out.println(instance);
        System.out.println(instance);

        System.out.println("=========反射破解========");
        Constructor<? extends LazyMan> constructor = instance.getClass().getDeclaredConstructor();
        constructor.setAccessible(true);
        LazyMan lazyMan = constructor.newInstance();
        System.out.println(lazyMan);

    }
    
//结果如下
======================
LazyMan的构造方法调用了!
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@506e1b77
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@506e1b77
=========反射破解========
LazyMan的构造方法调用了!
com.example.study.DesignPattern.单例模式.懒汉式单例.LazyMan@4fca772d

明显可以看出有2个不同的LazeMan实例对象,可见私有化的构造器在反射面前还是没有抵抗力

4.枚举式单例

因为java的反射机制不能破环枚举类信息,所有利用枚举类来创建单例才可以避免以上所有的问题,写法如下
INSTANCE就是EnumSingleton的一个实例

enum EnumSingleton{
    INSTANCE;
    public EnumSingleton getInstance(){
        return INSTANCE;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值