简体   繁体   English

如果在OOP中使用过多的单例和静态方法,会有什么风险?

[英]What's the risk if using too many singletons and static methods in OOP?

I've written OOP programs for almost two years. 我已经写了将近两年的OOP程序。 But recently I find that I always prefer using too many singletons and static methods in my OOP projects. 但是最近我发现我总是喜欢在OOP项目中使用太多的单例和静态方法。

For example, in order to decouple codes, I'd like to use MVC or something like 3-tier architecture. 例如,为了解耦代码,我想使用MVC或类似3层架构的东西。 I usually use Models to temporarily store information, such as user's login token or his or her profile. 我通常使用模型来临时存储信息,例如用户的登录令牌或他或她的个人资料。 I find that in most case, I just need one instance of a model class. 我发现在大多数情况下,我只需要一个模型类的实例。 So almost all of my Models are written in Singleton style. 因此,几乎所有我的模型都是以Singleton风格编写的。

And in the Business Logic Layer or Controller, I hardly can find a situation to use multi instances to call a same method, except for multithreading reasons. 而且在业务逻辑层或控制器中,除了多线程原因外,我几乎找不到使用多个实例来调用同一方法的情况。 That cause most of my BLL are constructed by static methods or class! 这导致我的大多数BLL是通过静态方法或类构造的!

I know this question is abstract and not really a good question for StackOverflow. 我知道这个问题很抽象,对于StackOverflow来说并不是一个好问题。 But I myself feel really confusing about this. 但是我自己对此感到非常困惑。 I think this kind of coding style does not really a OOP style, but I cannot find a better way to solve these logic problems above. 我认为这种编码风格并不是真正的OOP风格,但是我找不到解决上述逻辑问题的更好方法。

There is only one good reason to use a Singleton. 使用Singleton只有一个很好的理由。 When It is necessary that there is only one instance of the class. 何时只有一个类的实例是必要的。 I mean, It cannot be more of one instance. 我的意思是,这不能只是一个实例。

Examples: 例子:

  • Your logger. 您的记录器。 You open a file to save the data. 您打开一个文件以保存数据。 If other instance is called. 如果调用了其他实例。 You would have several log files... 您将有几个日志文件...

  • A class to send things to a printing machine. 将事物发送到打印机的类。 You will need to open the driver of the printer. 您将需要打开打印机的驱动程序。 If you create two of this you get errors trying to open twice the driver. 如果创建其中两个,则尝试两次打开驱动程序时会出错。

If you only create one instance of your classes, it means that you do not need more TODAY. 如果仅创建类的一个实例,则意味着您今天不需要更多。 Do not auto-constraint yourself. 不要自动约束自己。

It is a bad solution to use a pattern that was created for other purpose. 使用为其他目的而创建的模式是一个糟糕的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM