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

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

问题描述

我在 SO 中看到一些人评论单例模式是一种反模式.我想知道为什么?

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

推荐答案

测试

一个原因是单例不容易通过单元测试来处理.您无法控制实例化,并且就其本质而言,可能会在调用之间保持状态.

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).

Spring 等框架会控制它们对象的生命周期,经常会创建单例,但是这些对象是被框架注入到它们依赖的对象中的.因此,代码库本身不会将对象视为单例.

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();
}

你会注入计算器:

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

因此 Portfolio 对象不知道/关心 Calculator 存在多少个实例.测试可以注入一个虚拟的 Calculator 使测试变得容易.

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.

并发

通过将自己限制为对象的一个​​实例,线程化的选项是有限的.可能必须保护对单例对象的访问(例如,通过同步).如果您可以维护这些对象的多个实例,那么您可以根据正在运行的线程调整实例数量,并增加代码库的并发能力.

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 代码中实现单例模式(有时)被认为是 Java 世界中的反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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