为什么在Java代码中实现Singleton模式(有时被认为是Java世界中的反模式)? [英] Why implementing a Singleton pattern in Java code is (sometimes) considered an anti-pattern in Java world?

查看:94
本文介绍了为什么在Java代码中实现Singleton模式(有时被认为是Java世界中的反模式)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一些人在评论说Singleton Pattern是一种反模式。我想知道为什么?

解决方案

测试



一个原因是单身人员不容易处理单元测试。您不能控制实例化,而且它们的本质可能会保留调用的状态。



为此原因依赖注入很受欢迎。每个类都注入(配置)他们需要的类(而不是通过单例访问器派生),因此测试可以控制使用哪些依赖类实例(如果需要的话)提供嘲笑。



框架如Spring将控制其对象的生命周期,并经常创建单例,但这些对象由框架注入到其依赖对象中。因此,代码库本身不将对象视为单例。



而不是这个(例如)

  public class Portfolio {
private Calculator calc = Calculator.getCalculator();
}

您将注入计算器:

  public class Portfolio {
public Portfolio(Calculator c){
this.calc = c;
}
}

因此, code>对象不知道/关心 Calculator 存在多少个实例。



并发

>

通过限制对象的一个​​实例,线程的选项是有限的。对单体对象的访问可能必须被保护(例如通过同步)。如果您可以维护这些对象的多个实例,那么您可以根据已运行的线程定制实例数,并增加代码库的并发功能。


I have seen some people in SO commenting that Singleton Pattern is an anti-pattern. I want to know why ?

解决方案

Testing

One reason is that singletons aren't easy to handle with unit tests. You can't control the instantiation and by their very nature may retain state across invocations.

For that reason the principle of dependency injection is popular. Each class is injected (configured) with the classes they need to function (rather than derive via singleton accessors) and so tests can control which dependent class instances to use (and provide mocks if required).

Frameworks such as Spring will control the lifecycle of their objects and often create singletons, but these objects are injected into their dependent objects by the framework. Thus the codebase itself doesn't treat the objects as singletons.

e.g. rather than this (for example)

public class Portfolio {
   private Calculator calc = Calculator.getCalculator();
}

you would inject the calculator:

public class Portfolio {
   public Portfolio(Calculator c) {
      this.calc = c;
   }
}

Thus the Portfolio object doesn't know/care about how many instances of the Calculator exist. Tests can inject a dummy Calculator that make testing easy.

Concurrency

By limiting yourself to one instance of an object, the options for threading are limited. Access to the singleton object may have to be guarded (e.g. via synchronisation). If you can maintain multiple instances of those objects, then you can tailor then number of instances to the threads you have running, and increase the concurrent capabilities of your codebase.

这篇关于为什么在Java代码中实现Singleton模式(有时被认为是Java世界中的反模式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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