Java设计模式---单例模式

单例模式的几种实现方法,具体如下:

懒汉模式

public class Singleton{
    private static Singleton instance;

    private Singleton(){
    }

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

优点
- 可以延迟加载

缺点
- 多线程不安全

饿汉模式

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton(){}

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

优点
- 多线程安全

缺点
- 加载类时就初始化完成,无法延时加载

双重检查

public class Singleton {

    private static Singleton instance ;

    private Singleton(){}

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

优点
- 多线程安全
- 延迟加载

缺点
- 同步耗时

静态内部类

public class Singleton {

    private Singleton(){}

    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static Singleton instance = new Singleton();
    }
}

优点
- 多线程安全
- 延迟加载
- 耗时短(与双重检查相比)

用缓存实现

public class Singleton {

    private static final String KEY = "instance";

    private static Map<String, Singleton> map = new HashMap<>();

    private Singleton(){}

    public static Singleton getInstance(){
        Singleton singleton ;
        if (map.get(KEY) == null){
            singleton = new Singleton();
            map.put(KEY, singleton);
        } else {
            singleton = map.get(KEY);
        }
        return singleton;
    }
}

优点
- 线程安全

缺点
- 占用内存较大

枚举模式

public enum Singleton {

    instance;

    public void operate(){}
}

优点
- 简洁

缺点
- 占用内存大(Android官方不推荐使用枚举)

更多文章请移步我的博客:DevWiki Bolg

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DevWiki

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值