开发者

Are singleton network event processors okay?

开发者 https://www.devze.com 2022-12-22 20:43 出处:网络
Suppose you have a system on the other side of a network that sends events and data that needs t开发者_如何学运维o be cached to some intermediate broker.

Suppose you have a system on the other side of a network that sends events and data that needs t开发者_如何学运维o be cached to some intermediate broker.

Instead of giving every component of your application that needs to be informed of such events a new subscription to the broker, I decide for performance and simplicity (the third party library that handles broker subscriptions isnt pretty) I should have only one Event Processor that subscribes to the broker and programatically fires events as it receives them to subscribed listeners provided by the components. The cached data can also be shared from this singleton. This will greatly reduce network connections.

However according to most discussions about singletons, they are always evil PERIOD unless for concurrency reasons or hardware reasons you need only one access point. This is not my situation since every component could have their own subscription and their own personal cache of data since all the data can be requested over the broker. However this could easily add 200 more network connections.

Because singletons are evil does that mean 200 more connections to a broker with 200 copies of data is better than using singleton I don't need to use? After all this slows things down quite a bit but its not game breaking, the application is still usable.


There's nothing inherently wrong with your broker client object servicing multiple clients within your process.

All the talk about singletons being evil is really about global variables being evil. A singleton becomes evil because it provides a static access point to mutable state, not because there is only one instance of it.

In that light, you might want to use dependency injection to hook it up rather than calling Broker.getInstance(). This avoids client code making the assumption that it is in fact a singleton.

0

精彩评论

暂无评论...
验证码 换一张
取 消