设计模式-创建型-Singleton

本质——唯一实例

一、what

一个类在整个系统中只有一个实例;

通过内部private构造方法创建;

多线程共享一个实例;

占用特定的内存区域;

常驻能内存;

二、why

在内存中只有一个对象,节省内存空间。避免频繁的创建销毁对象,可以提高性能。避免对共享资源的多重占用。可以全局访问。

三、how

内部类、饿汉、静态代码块都是利用了static的特性,还有利用Enum特性。

 

/**
 * @Description: 饿汉模式,线程安全
 * @date 2018-05-21 23:18
 */
public class HungerModel {
    private static HungerModel hungerModel = new HungerModel();
    private HungerModel(){}
    public static HungerModel getInstance(){
        return hungerModel;
    }
}
/**
 * @Description: 使用内部静态类实现单例
 * @date 2018-05-21 23:25
 */
public class InnerClass {
    private static class InnerClassCreater{
        private static InnerClass innerClass = new InnerClass();
    }
    private InnerClass(){}
    public static InnerClass getInstance(){
        return InnerClassCreater.innerClass;
    }
}
/**
 * @Description: 懒汉模式单例的线程安全写法
 * @date 2018-05-21 23:10
 */
public class LazyModel {
    private static LazyModel lazyModel;
    private LazyModel(){}
    public static LazyModel getInstance(){
        if(null != lazyModel){
        }else{
            // 模拟一些逻辑
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (LazyModel.class) {
                if (null == lazyModel) {
                    lazyModel = new LazyModel();
                }
            }
        }
        return lazyModel;
    }
}
/**
 * @Description: 使用静态代码块实现单例
 * @date 2018-05-21 23:33
 */
public class StaticModel {
    private static StaticModel staticModel = null;
    private StaticModel(){}
    static{
        staticModel = new StaticModel();
    }
    public static StaticModel getInstance(){
        return staticModel;
    }
}

/**
 * @Description: 利用Enum特性,牛逼推荐的一种方式
 * @date 2018-06-17 23:08
 */
public enum ResourceEnum {
    INSTANCE;

    private Resource instance;
    ResourceEnum(){
        instance = new Resource();
    }

    public Resource getResourceInstance(){
        return instance;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值