java单例模式,所有变量应该是类变量? [英] java singleton pattern, should all variables be class variables?

查看:784
本文介绍了java单例模式,所有变量应该是类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个类实现单例模式,应该将所有的变量声明为静态吗?



有什么理由不应该被声明为静态吗?是否有所作为?

解决方案

否。单例模式只意味着单一实例是唯一的实例 - 它并不意味着使所有的静态访问。



单例模式为您提供了所有的好处一个单一实例,而不牺牲测试和重构代码的能力。



编辑:



我想要做的是,如何消耗功能(取决于上下文)之间的差异以及如何初始化功能。



在大多数情况下,您的对象只能拥有单个实例(例如,在最终生产系统中)可能是合适的。但是,如果强制它成为唯一的选择,那么还有其他的上下文(如测试)会变得更加困难。



另外,使静态的东西比只有我的一个类的一个实例应该可以访问有更重要的意义 - 这通常是意图。

$另外,在我所处理的软件中,对象的初始化和生命周期通常由别人控制(我在这里谈论DI) - 并且使静态的东西真的不会在这里帮忙。


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.

这篇关于java单例模式,所有变量应该是类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆