当去静态类? [英] When to go for static classes?

查看:115
本文介绍了当去静态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我codeA解决方案,这是我倾向于要么使用大量的静态类或没有在所有。例如,在最近的一个项目我已经通过一些箍,而不是静态的唯一派一类的一些字符串/布尔/日期数据是这样的数据保持类。其他一切(3 pretty的巨额类不同的处理任务)是静态的。

Whenever I code a solution to something I tend to either use a lot of static classes or none at all. For example in a recent project I had to send a class with some string/bool/datetime data through a number of hoops and the only thing that wasn't static was this data-holding class. Everything else (3 pretty hefty classes with different processing responsibilities) were static.

我想我要问这里是一些输入时(为什么)我应避免使用静态类为这些过程X,输出Y的情况。它是确定始终使用他们,只要他们的工作还是我拍摄自己的脚有关的可扩展性,插件支持等?

I think what I'm asking for here is some input on when (and why) I should avoid using static classes for these "process X, output Y" cases. Is it ok to always use them as long as they work or am I shooting myself in the foot concerning scalability, plugin-support etc?

我希望这是一个好问题要问在这里。我不要求有关静态类是否是更好的说法 - 就当我应避免使用它们只是输入

I hope this is an OK question to ask here. I'm not asking for an argument concerning whether or not static classes are "better" - just input on when I should avoid using them.

推荐答案

不过这两个问题仍然是一个有点相同。在静态类我主要关注的是继承和可访问性。

Still the two questions remain a bit the same. My main concern on static classes is inheritance and accessability.

在使用静态类(公众在最坏情况下),每个人都能够访问你的流程和功能。这是大多数的时候不是你想要的。这是太容易得到你的函数的一些对象,并做了一些修改。因此,依赖注入是很好用。 (传你要在参数修改的对象,这是在这种情况下,你的处理对象)。

When using a static class (public in the worst case), everyone is able to access your processes and functions. Which is most of the time not what you want. It is too easy for some object to get to your functions and do some modifications. Therefore, dependency injection is nice to use. (Pass the object you want to modify in the parameters, which is in this case your process-object).

要prevent他人操纵你的处理对象,为什么不尝试使用某种单例模式(或者甚至是前单例模式),所以居然还有一个真正的对象倾诉?您可以传递对象到你的函数的参数,如果事情应该修改。然后,你可以有一个管理器,握着你的处理对象。别人不应该得到对象

To prevent others from manipulating your process-object, why not try to use some kind of singleton pattern (or even an ex-singleton pattern), so there is actually a real object to talk to? You can pass the object into the parameters of your functions if something should be modified. And then you can just have one manager that holds your process-object. Others shouldn't get to the object.

静态类也很难承受。覆盖静态方法似乎有点陌生。所以,如果你相信这个过程不会是唯一的过程中,还有一些更具体的进程将被你创建的,则静态类应尽量避免为好。​​

Static classes are also hard to inherit. Overriding static methods seems a bit strange. So if you are sure that the process will not be the only process, and some more specific processes will be created by you, then a static class should be avoided as well.

这篇关于当去静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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