java单例变量,java单例模式,所有变量应该是类变量?

If a class implements a singleton pattern, should all the variables be declared static?

Is there any reason they shouldn't be declared static? Does it make a difference?

解决方案

No. The singleton pattern just means that a single instance is the only instance -- it does not mean "make everything statically accessible".

The singleton pattern gives you all the benefits of a "single instance", without sacrificing the ability to test and refactor your code.

Edit:

The point I'm trying to make is that there is a difference between how functionality should be consumed (which depends on context), and how functionality should be initialized.

It may be appropriate that in most cases your object will only ever have a single instance (for example, in your final production system). But there are also other contexts (like testing) that are made much more difficult if you force it to be the only choice.

Also, making something static has more significant implications than just "only one instance of my class should be accessible" -- which is usually the intention.

Further, in software I've worked on, the initialization and lifecycle of objects is often controlled by someone else (I'm talking about DI here) -- and making something static really doesn't help here.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值