我应该如何重构我的代码以删除不必要的单例? [英] How should I refactor my code to remove unnecessary singletons?

查看:74
本文介绍了我应该如何重构我的代码以删除不必要的单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我第一次开始看到反单音的评论时,我感到很困惑.我在最近的一些项目中使用了单例模式,并且效果很好.事实上,我已经使用了很多次.

I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.

现在,遇到一些问题后,阅读这个 SO问题,尤其是这篇博客文章,我了解我为网站带来的邪恶世界.

Now, after running into some problems, reading this SO question, and especially this blog post, I understand the evil that I have brought into the world.

所以:我该如何从现有代码中删除单例?

So: How do I go about removing singletons from existing code?

例如:
在零售商店管理程序中,我使用了MVC模式.我的模型对象描述了商店,用户界面是视图,并且我有一组充当两者之间联络人的控制器.伟大的.除了将Store变成一个单例(因为该应用程序一次只能管理一个商店),而且我还将我的大多数Controller类也变成了Singleton(一个mainWindow,一个menuBar,一个productEditor ...).现在,我的大多数Controller类都可以访问其他单例,如下所示:

For example:
In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:

Store managedStore = Store::getInstance();
managedStore.doSomething();
managedStore.doSomethingElse();
//etc.

我应该改为:

  1. 为每个对象创建一个实例,并将引用传递给需要访问它们的每个对象?
  2. 使用全局变量?
  3. 还有别的吗?
  1. Create one instance of each object and pass references to every object that needs access to them?
  2. Use globals?
  3. Something else?

全局变量仍然很糟糕,但至少它们不会成为

Globals would still be bad, but at least they wouldn't be pretending.

我看到#1很快导致构造函数调用急剧膨胀:

I see #1 quickly leading to horribly inflated constructor calls:

someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)

还有其他人经历过吗?在公共变量而不是全局变量或单例变量的情况下,给许多单独的类赋予访问权限的OO方法是什么?

Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton?

推荐答案

依赖注入是您的朋友.

优秀的Google测试博客上查看这些帖子:

  • Singletons are pathologic liars (but you probably already understand this if you are asking this question)
  • A talk on Dependency Injection
  • Guide to Writing Testable Code

希望有人为C ++世界做了一个DI框架/容器? Google似乎发布了 C ++测试框架

Hopefully someone has made a DI framework/container for the C++ world? Looks like Google has released a C++ Testing Framework and a C++ Mocking Framework, which might help you out.

这篇关于我应该如何重构我的代码以删除不必要的单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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