单身否 [英] Singleton or not

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

问题描述

我有一个Windows服务运行。在这个服务我已经托管了一些服务(WCF)。
我需要一些内存数据持有者类。只要Windows服务正在运行,此类的目的就是持有不持久的数据。
此类必须通过WCF服务访问。他们在这个类中放了一些值,或从这个类中检索一些值。



首先,我想到的是一个单例类。我认为这个模式适合这个情况。但是后来我读了一些帖子,单身人士的实际上并不是那么好。



那么这种情况有什么选择吗?还是单身吗?工厂方法怎么样?但是那么在哪里可以找到对象的参考?

解决方案

Singleton设计模式应该被重新标记为反模式。 它是邪恶的。不要使用它。



一个更好的选择是使用依赖注入(DI)并注入一个类,您可以使用它来保存非常持久的数据。



很多人都没有意识到WCF支持依赖注入(DI)模式,例如构造函数注入没有太多的麻烦。



如果将注入的类作为长期存在的对象(通常称为Singleton 生命周期样式),而不是与Singleton设计模式混淆),您可以继续访问调用之间的相同实例。



但是,无论何时使用共享对象(无论您使用Singleton作为设计模式或一生的风格),您必须准备好处理多线程问题



在许多其他事情中,这篇文章 des在没有默认构造函数的情况下,如何将依赖关系注入到WCF服务实现中。


I have a windows service running.Inside this service I have hosted some service (WCF). I need to have some kind of a "in memory data holder" class. The purpose of this class is to hold not-persistant data as long as the windows service is running. This class must be accessible thru the WCF services. They put some values in this class or retrieve some values from this class.

First thing what come across my mind was a singleton class.I think this pattern fits perfect for this situation. But then I read some post that the singleton class isnt actually that good.

So is there any alternative for this kind of situation? Or is the singleton for this ok ? What about a Factory method ? But then Where would I find the references for the objcects ?

解决方案

The Singleton design pattern should really be relabeled as an anti-pattern. It is evil. Don't use it.

A better alternative is to use Dependency Injection (DI) and inject a class which you can use to hold the non-persistent data you need.

A lot of people don't realize that WCF supports Dependency Injection (DI) patterns such as Constructor Injection without too much hassle.

If you scope the injected class as a long-lived object (usually referred to as Singleton lifetime style, but not to be confused with the Singleton design pattern) you can keep accessing the same instance between calls.

However, whenever you use shared objects (whether you use Singleton as a design pattern or a lifetime style) you must be prepared to handle multithreading issues.

Among many other things, this post describes how to inject dependencies into a WCF service implementation when it doesn't have a default constructor.

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

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