Java设计模式-单例模式

一、单例模式

所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。

二、单例模式的八种方法

1.饿汉式(静态常量)

// 1.饿汉式(静态变量)
class Singleton1 {

    // 1) 构造器私有化
    private Singleton1() {

    }

    // 2) 本类内部创建对象实例
    private final static Singleton1 instance = new Singleton1();

    // 3) 提供一个公有的静态方法,返回实例对象
    public static Singleton1 getInstance() {
        return instance;
    }
}

结论:这种单例模式可用,可能造成内存浪费

2.饿汉式(静态代码块)

// 2.饿汉式(静态代码块)
class Singleton2 {

    private Singleton2() {

    }

    private final static Singleton2 instance;

    static {
        instance = new Singleton2();
    }

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

结论:这种单例模式可用,可能造成内存浪费

3.懒汉式(线程不安全)

// 3.懒汉式(线程不安全)
class Singleton3 {

    private Singleton3() {

    }

    private static Singleton3 instance;

    public static Singleton3 getInstance() {
        if (instance == null)
            instance = new Singleton3();
        return instance;
    }
}

结论:在实际开发中,不要使用这种方式

4.懒汉式(线程安全,同步方法)

// 4.懒汉式(线程安全,同步方法)
class Singleton4 {

    private Singleton4() {

    }

    private static Singleton4 instance;

    // 加入同步处理代码,解决线程安全问题
    public static synchronized Singleton4 getInstance() {
        if (instance == null)
            instance = new Singleton4();
        return instance;
    }
}

结论:效率太低,在实际开发中,不推荐使用这种方式

5.懒汉式(线程安全,同步代码块)

// 5.懒汉式(线程安全,同步代码块)
class Singleton5 {

    private Singleton5() {

    }

    private static Singleton5 instance;

    public static Singleton5 getInstance() {
        if (instance == null) {
            synchronized (Singleton5.class) {
                instance = new Singleton5();
            }
        }
        return instance;
    }
}

结论:这种同步并不能起到线程同步的作用,在实际开发中,不能使用这种方式

6.双重检查

// 6.双重检查
class Singleton6 {

    private Singleton6() {

    }

    private static Singleton6 instance;

    public static Singleton6 getInstance() {
        if (instance == null) {
            synchronized (Singleton6.class) {
                if (instance == null)
                    instance = new Singleton6();
            }
        }
        return instance;
    }
}

结论:在实际开发中,推荐使用这种单例设计模式

7.静态内部类

// 7.静态内部类
class Singleton7 {

    private Singleton7() {

    }

    private static class SingletonInstance {
        private static final Singleton7 INSTANCE = new Singleton7();
    }

    public static Singleton7 getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

结论:采用了类装载的机制来保证初始化实例时只有一个线程,推荐使用

8.枚举

// 8.枚举
enum Singleton8 {
    INSTANCE;
}

结论:不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象,推荐使用

三、单例模式的使用

在JDK中的使用:Runtime类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值