在实际应用中究竟使用Singleton Pattern? [英] Where exactly the Singleton Pattern is used in real application?

查看:178
本文介绍了在实际应用中究竟使用Singleton Pattern?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是好奇使用单身模式...
我知道模式是如何工作的以及它可以在哪里使用但我个人从未在任何实际应用中使用过。
可以有人给出一个可以使用它的例子..
如果有人可以解释它们在实际应用中的使用方式和位置,我真的很感激。
谢谢,
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

推荐答案

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

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 派生自己的类,并以这种方式创建额外的实例 - 但是通常使用作为单身人士。

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

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

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


每个Java应用程序都有一个
类的Runtime实例,允许
应用程序与
环境接口应用程序
正在运行。当前运行时可以是从getRuntime方法获得的

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.

这几乎是单例的定义:)

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

现在单身人士模式主要是这些天皱起了眉头 - 它引入了紧密耦合,并使使用单身人士的东西更难以测试,因为你可以不容易嘲笑那个组件。如果没有它可以逃脱,那就更好了。尽可能地注入您的依赖项。

Now the singleton pattern is mostly frowned 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.

这篇关于在实际应用中究竟使用Singleton Pattern?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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