大话设计模式学习笔记(21)——单例模式

源码git地址 https://github.com/dlovetco/designMode

问题提出

确保一个实体类在整个程序运行中只能被实例化一次。即只能有一个该类的对象。

看到这个问题,有一定编程基础的同学肯定能够想到用单例模式。本篇博客我就来写一下单例模式的5种不同的实现方法。

package singleton;

public class Singleton {
    public static void main(String[] args) {

    }
}

/**
 * 懒汉式 所谓懒汉即只有当需要这个对象的时候才会去生成
 */
class Singleton1 {
    private static Singleton1 singleton1;

    private Singleton1() {

    }

    public static Singleton1 getInstance() {
        if (singleton1 == null) {
            singleton1 = new Singleton1();
        }
        return singleton1;
    }
}

/**
 * 饿汉式 所谓饿汉就是即使系统不需要类中已经迫不及待的生成对象等待系统调用了
 */
class Singleton2 {
    private static Singleton2 singleton2 = new Singleton2();

    private Singleton2() {

    }

    public static Singleton2 getInstance() {
        return singleton2;
    }
}

/**
 * 考虑到多线程中单例 则需要考虑到锁机制(只有饱汉式才需要考虑多线程情况)
 *
 */
class Singleton3 {
    private static Singleton3 singleton3;

    private Singleton3() {

    }

    //不建议这么写。在低版本jdk中都不能够保证正确性
//    public static Singleton3 getInstance() {
//        if (singleton3 == null) {
//            synchronized (Singleton3.class){
//                if (singleton3 == null) {
//                    singleton3 = new Singleton3();
//                }
//            }
//
//        }
//        return singleton3;
//    }
    //取而代之应该用这种简单的写法
    public static synchronized Singleton3 getSingleton3() {
        if (singleton3 == null) {
            singleton3 = new Singleton3();
        }
        return singleton3;
    }
}

/**
 * 静态内部类
 */
class Singleton4 {
    private Singleton4() {

    }

    public static Singleton4 getInstance() {
        return innerSingleton4.singleton4;
    }

    private static class innerSingleton4{
        private static Singleton4 singleton4 = new Singleton4();
    }
}

/**
 * 枚举类 极力推荐这种写法 简单暴力不怕反射~~~
 */
enum  Singleton5 {
    SINGLETON;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值