单例设计模式

单例模式

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

1.饿汉式

即使只调用了一个静态属性,对象也已经加载好了,对于存在重量级对象的情况,创建了不用会造成资源的浪费;
1.将构造器私有化
2.在类的内部直接创建对象(该对象是static的)
3.提供一个公共的static方法,返回该对象

public class SingleTon01 {
    public static void main(String[] args) {
        GirlFriend girlFriend = GirlFriend.getInstance();
        System.out.println(GirlFriend.n1);
    }
}
class GirlFriend {
    private String name;
    private static int n1 = 100;
    //为了能在静态方法中,返回wife,将其修饰为static,即静态变量
    private static GirlFriend wife = new GirlFriend("小红红");//调用有参构造器
    //如何保障我们只能创建一个GirlFriend对象
    //步骤[单例模式-饿汉式]
    //1.将构造器私有化
    //2.在类的内部直接创建一个对象
    //3.提供一个公共的static方法,返回wife对象
    private GirlFriend(String name) {
        this.name = name;
    }
    //静态方法
    public static GirlFriend getInstance() {
        return wife;
    }
}

2.懒汉式

只有使用了才会创建,存在线程安全问题

public class SingleTon01 {
    public static void main(String[] args) {
        System.out.println(Cat.n2);//创建了一个Cat引用,构造器不会被调用
        Cat cat = Cat.getInstance();
    }
}
class Cat {
    private String name;
    public static int n2 = 200;
    //2.创建一个静态对象
    private static Cat cat;//null
    //步骤
    //1.构造器私有化,不能随便被创建了
    private Cat(String name) {
        System.out.println("Cat 构造器被调用");
        this.name = name;
    }
    //3.提供一个公共的static方法,可以返回一个Cat对象
    public static Cat getInstance() {
        if(cat == null) {
            return new Cat("小花猫");
        }
        return cat;
    }
}

3.区别

饿汉式是类加载的时候就创建了对象,而懒汉时是使用的时候创建对象。

4.饿汉式经典应用

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() {}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

~ 小团子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值