Singletons的替代方法 [英] Alternatives to Singletons

查看:92
本文介绍了Singletons的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这涉及到: Singletons有什么不好

你能给我一些例子,使用其他技术可以避免单身人士吗?
我需要在C ++中使用这个,所以你可以用C ++的具体技术给出例子。



更清楚:如何实现文件管理器,资源管理器,日志管理器等,而不使用单例。

解决方案

简单:创建文件管理器(或任何)类的单个实例,然后根据需要将它传递到应用程序内部。很多将取决于你的应用程序结构,但通常你有一些类型的控制器对象,在应用程序中创建其他重要的对象。这可能是实例化文件管理器的对象,然后将它传递给需要文件管理器的其他对象。



如果你使用单例,必须不超过一个类的一个实例,这通常是好的。如果你使用它,因为单例是一个全局可访问的对象,让你避免思考其他对象如何相互交谈和每个对象负责,这就是你开始遇到问题的地方。



文件管理器是一个很好的例子。起初,似乎应该只有零个或一个文件管理器对象的实例。但是这是必要的吗?您不能同时在一台计算机上有两个文件系统?


This is related to: What is so bad about Singletons

Can you give me some examples where Singletons can be avoided using other techniques? I need to use this in C++ so you can give examples with C++ specific techniques.

To be more clear: How you would implement a file manager, resource manager, log manager, etc without singletons.

解决方案

Simple: create a single instance of your file manager (or whatever) class, and then pass it around inside your application as necessary. Much will depend on your application structure, but typically you have some sort of controller object that creates the other important objects in the application. That might be the object to instantiate the file manager, and then pass it to the other objects it creates that need a file manager.

If you're using a singleton because there MUST be no more than one instance of a certain class, that's usually okay. If you're using it because a singleton is a globally-accessible object that lets you avoid thinking about how the other objects talk to each other and what each object is responsible for, that's where you start to run into problems.

The file manager is a nice example. At first it seems like there should only ever be zero or one instances of the file manager object. But is that necessary? Can't you have two file systems on one machine at the same time?

这篇关于Singletons的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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