首页 > 其他 > 详细

单例设计模式

时间:2021-08-08 16:04:43      阅读:20      评论:0      收藏:0      [点我收藏+]

饿汉单例模式:1.构造方法私有化,不能在类的外部使用new关键字创建对象

                          2.new一个实例化对象,用private static修饰

          3.静态方法返回这个对象

public class Singleton1 {

    private Singleton1(){
    }

    public static final Singleton1 s = new Singleton1();

    public static Singleton1 getInstance(){
        return s;
    }

}

饱汉单例设计模式:1.构造方法私有化,不能在类的外部使用new关键字创建对象

         2.仅仅创建一个实例化对象,也通过private static 修饰

            3.静态方法返回对象,通过判断语句,如果为null创建对象,其他返回

public class Singleton2 {
    private Singleton2(){
    }
    private static Singleton2 s;

    public static Singleton2 getInstance() {
        if (s == null) {
            s = new Singleton2();
        }
        return s;
    }
}

 

单例设计模式

原文:https://www.cnblogs.com/zyl777/p/15114378.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!