Java 实际应用中究竟在哪里使用了单例模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3192095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:16:04  来源:igfitidea点击:

Where exactly the Singleton Pattern is used in real application?

javasingleton

提问by swati

I was just curious where exactly the singleton pattern is used... I know how the pattern works and where it can be used but i personally never used in any real application. Can some one give an example where it can be used.. I would really appreciate if some one can explain how and where they have used in real application. Thanks, Swati

我只是好奇单例模式到底在哪里使用......我知道该模式是如何工作的以及它可以在哪里使用,但我个人从未在任何实际应用程序中使用过。有人可以举一个可以使用它的例子吗?如果有人可以解释他们在实际应用中的使用方式和位置,我将不胜感激。谢谢,斯瓦蒂

回答by Jon Skeet

Typically singletons are used for global configuration. The simplest example would be LogManager- there's a static LogManager.getLogManager()method, and a single global instance is used.

通常单例用于全局配置。最简单的例子是LogManager- 有一个静态LogManager.getLogManager()方法,并且使用了一个全局实例。

In fact this isn't a "true" singleton as you can derive your own class from LogManagerand create extra instances that way - but it's typically usedas a singleton.

事实上,这不是“真正的”单例,因为您可以从中派生自己的类LogManager并以这种方式创建额外的实例 - 但它通常用作单例。

Another example would be java.lang.Runtime- from the docs:

另一个例子是java.lang.Runtime- 来自文档:

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

每个 Java 应用程序都有一个 Runtime 类的单个实例,它允许应用程序与应用程序运行的环境进行交互。可以从 getRuntime 方法获取当前运行时。

That's pretty much the definition of a singleton :)

这几乎是单身人士的定义:)

Now the singleton pattern is mostlyfrowned upon these days - it introduces tight coupling, and makes things which use the singleton harder to test, as you can't easily mock out that component. If you can get away without it, so much the better. Inject your dependencies where possible instead.

现在单例模式现在大多不受欢迎——它引入了紧密耦合,并使使用单例的东西更难测试,因为你不能轻易地模拟出那个组件。如果你能在没有它的情况下逃脱,那就更好了。在可能的情况下注入您的依赖项。

回答by Florian

Some examples:

一些例子:

  • Hardware access
  • Database connections
  • Config files
  • 硬件访问
  • 数据库连接
  • 配置文件

回答by Max Leske

I used a singleton (actually a couple of them) in an application that used pureMVC. We were unhappy about the complexity this framework introduced (it became complicated and tiering to track method calls through the mvc layers). So we used a central singleton as a mediator to better separate the layers from each other.

我在一个使用 pureMVC 的应用程序中使用了一个单例(实际上是几个)。我们对这个框架引入的复杂性感到不满(通过 mvc 层跟踪方法调用变得复杂和分层)。所以我们使用一个中央单例作为中介来更好地将层彼此分开。

回答by Manaf Abu.Rous

I used the singleton pattern in an online Football Team Store System. we applied the singleton pattern to a ShoppingCart class.

我在在线足球队商店系统中使用了单例模式。我们将单例模式应用于 ShoppingCart 类。

You only needed one instance of the cart per an application instance. so the singleton seemed like it's the best fit for that situation.

每个应用程序实例只需要一个购物车实例。所以单身似乎最适合这种情况。

回答by ferosekhanj

Singleton is a nice design pattern. Before deciding on the pattern first do an in depth analysis of your problem and the solution. If in your solution some object has only one instance and you want to model that in your design then you should use singleton pattern. For example if you are modelling a PC in the software there can be only one instance of a PC with respect to your running program. As Jon Skeet said java.lang.Runtime is modelled as a singleton because for all the java objects that are loaded and running inside a java runtime there is only one instance of runtime.

Singleton 是一种很好的设计模式。在决定模式之前,首先对您的问题和解决方案进行深入分析。如果在您的解决方案中某个对象只有一个实例并且您想在您的设计中对其进行建模,那么您应该使用单例模式。例如,如果您在软件中对 PC 进行建模,则对于您正在运行的程序而言,可能只有一个 PC 实例。正如 Jon Skeet 所说,java.lang.Runtime 被建模为单例,因为对于在 java 运行时中加载和运行的所有 java 对象,只有一个运行时实例。

Again lot of times it is used for the wrong reasons. Never create a singleton so that you can easily access the object (like Object::instance() ) from anywhere without passing the object around. The is the worst use I have ever come across.

再次很多时候它被用于错误的原因。永远不要创建单例,以便您可以从任何地方轻松访问对象(如 Object::instance() )而无需传递对象。这是我遇到过的最糟糕的用法。

回答by Dead Programmer

For example running a trial version of a software with one license and one database connection ,that uses singleton pattern in real word. may be the guru jon skeet can provide example like this.

例如,运行具有一个许可证和一个数据库连接的软件的试用版,该软件在现实世界中使用单例模式。可能是大师 jon skeet 可以提供这样的例子。

回答by Akhil Gupta

Singleton Pattern can be used for loading the configuration , say in a web application, we are supposed to generate a file which is to be stored somewhere in the server. Now, that location can fetched from a config file(properties file) using a singleton class.since the location is to be unique and might change frequently in future, so we use a config file so as can be modified without deploying the application so as to reflect the changes and location will be global and unique through out the application

单例模式可用于加载配置,比如在 Web 应用程序中,我们应该生成一个文件,该文件将存储在服务器的某个位置。现在,可以使用单例类从配置文件(属性文件)中获取该位置。由于该位置是唯一的并且将来可能会经常更改,因此我们使用配置文件以便可以在不部署应用程序的情况下进行修改以反映更改和位置将在整个应用程序中是全球性和唯一性的

回答by Franco Omar Castillo Bello

I use a media player in my android app, so I extend the mediaplayer class, and used the singleton pattern because I need only one instance, and be able to call the same instance in any other part of my app for check if is playing, or what file is current playing.

我在我的 android 应用程序中使用媒体播放器,所以我扩展了 mediaplayer 类,并使用了单例模式,因为我只需要一个实例,并且能够在我的应用程序的任何其他部分调用同一个实例来检查是否正在播放,或者当前正在播放什么文件。

Hope it helps you, regards!!!!

希望能帮到你,加油!!!!

回答by netblogger

Singleton pattern is generally useful when the object that is created once and shared across different threads/Applications. Consider the case that you are implementing the properties load class for a printer.

当对象创建一次并在不同线程/应用程序之间共享时,单例模式通常很有用。考虑您正在为打印机实现属性加载类的情况。

Now Printers can be of variant properties. For eg:- Mono Printer, Color Printer, Automatic Scanner Support Printer and so on...

现在打印机可以具有变体属性。例如:- 单色打印机、彩色打印机、自动扫描仪支持打印机等...

Every time on boot this config file has to load to enable a few buttons/ applications on the UI say tab or any Printer UI.

每次启动时,必须加载此配置文件以启用 UI 选项卡或任何打印机 UI 上的几个按钮/应用程序。

The value of the supported features are stored in form of a config table like say 1 if feature supported and 0 if not supported.

支持的功能的值以配置表的形式存储,例如如果功能支持则为 1,如果不支持则为 0。

Based on the supported features we enable disable certain functionalities and application on the UI. Now this config file location in case of printers manufactured by a single company are always stored at a fixed path.

根据支持的功能,我们启用禁用 UI 上的某些功能和应用程序。现在,对于单个公司制造的打印机,此配置文件位置始终存储在固定路径中。

The file values would change/would be read only in the following scenarios:- 1. On Boot. 2. on Addition or deletion of any new hardware peripheral.

文件值将在以下情况下更改/只能读取:- 1. 启动时。2. 关于添加或删除任何新硬件外围设备。

We can use a singleton class to implement the reading of configuration files. As the same values i.e. the config does not change on UI intervention and can be changed only on hardware intervention.

我们可以使用一个单例类来实现配置文件的读取。作为相同的值,即配置不会在 UI 干预时更改,只能在硬件干预时更改。

This is one example I can think of where we can implement Singleton design pattern.

这是我能想到的一个例子,我们可以在哪里实现单例设计模式。

回答by Arun Raaj

When you use Logger, you use Singleton pattern for the Logger class. In case it is not Singleton, every client will have its own Logger object and there will be concurrent access on the Logger instance in Multithreaded environment, and multiple clients will create/write to the Log file concurrently, this leads to data corruption.

使用 Logger 时,对 Logger 类使用单例模式。如果不是Singleton,每个客户端都会有自己的Logger对象,多线程环境下Logger实例会并发访问,多个客户端同时创建/写入Log文件,导致数据损坏。