设计模式入门:单例模式

个人公众号【爱做梦的锤子】,全网同id,个站 http://te-amo.site,欢迎关注,里面会分享更多有用知识,还有我的私密照片
文章中部分定义和解释性文字,都是引用百度百科,主要的代码及场景应用为本人原创

在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。

场景:在设计我的个人网站时,有一个站点配置的类,用于存放配置信息(备案号,联系方式等),这个类要求整个系统只能有一个,所以就可以采用单例模式

设计

单例三要素

  • 私有的构造方法
  • 指向自己实例的私有静态引用
  • 以自己实例为返回值的静态的公有的方法

介绍三种设计方式

  • 饿汉模式:不用考虑并发问题,但是不管是否使用该实例,都会在类加载时就创建实例,大量使用该方式会造成内存的不必要开销
  • 懒汉模式(双重检验):可以解决并发问题,但每次获取单例对象时都要判空,可能会影响性能
  • 懒汉模式(静态内部类):解决并发问题,也不需要进行判空,比较好的解决了以上两个问题(推荐

实现

代码地址:https://github.com/telundusiji/designpattern

饿汉模式

public class HungerSingleton {
    private final static HungerSingleton singleton = new HungerSingleton();
    private HungerSingleton(){}
    public static HungerSingleton getInstance(){
        return singleton;
    }

}

懒汉模式 双重校验

public class LazySingletonTypeOne {
    private static volatile LazySingletonTypeOne singleton = null;
    private LazySingletonTypeOne(){}
    public static LazySingletonTypeOne getInstance(){
        if(singleton == null){
            synchronized (LazySingletonTypeOne.class){
                if(singleton == null){
                    singleton = new LazySingletonTypeOne();
                }
            }
        }
        return singleton;
    }
}

懒汉模式 静态内部类

public class LazySingletonTypeTow {
    private LazySingletonTypeTow(){}
    private static class innerClass{
        public final static LazySingletonTypeTow singleton = new LazySingletonTypeTow();
    }
    public static LazySingletonTypeTow getInstance(){
        return innerClass.singleton;
    }
}

经典应用

JDK 中的Runtime类,该类可用来执行DOS命令

Runtime 单例部分的代码

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}
    //...
}

优缺点

优点

  • 实例控制:单例模式会阻止其他对象实例化其自己的单例对象的副本,从而确保所有对象都访问唯一实例。

缺点

  • 对象生存期:如果实例化的对象长时间不被利用,系统会认为是垃圾而被回收,这将导致对象状态的丢失

个人公众号【爱做梦的锤子】,全网同id,个站 http://te-amo.site,欢迎关注,里面会分享更多有用知识,还有我的私密照片

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值