开发者

Alternative to Observer Pattern

开发者 https://www.devze.com 2023-02-14 14:30 出处:网络
Does anyone know of an alternative to the Observer a.k开发者_运维问答.a. Listener pattern? I\'m interested in something that would work well in an asynchronous

Does anyone know of an alternative to the Observer a.k开发者_运维问答.a. Listener pattern? I'm interested in something that would work well in an asynchronous environment.

The problem I'm facing is that I have an application which uses this pattern a lot, which is not a bad thing per se, but it becomes a bottleneck as the number of listeners increases. Combined with threading primitives (mutexes, critical sections - of course in my specific environment) the hit on performance is really bad.


How about Message Queue?


If there are too many observers, so the thread being observed is not making any progress, then it might be wise to reverse the relationship. Rather than have the observed thread call out to each and every observer, it may be better to have the observers wait on something like a condition variable or event associated with the observed thread. The observer code can then block, waiting for the condition variable to be signalled. The observed thread can then just signal the condition variable rather than calling into the observers; the observers can notice the signal and process the consequences in their own time.


Please take a look at it if reducing listeners in your code is your primary objective Jeffrey Richter and his AsyncEnumerator. This technique makes asynchronous programmin look more like synchronous.

With this technique your single method could issue an Asynch call and resto fo the method act as an event handler, therefore whole of the invokation and event listener code could be clubbed as one fucntion.


Difficult to say without a more concrete description but the Mediator pattern is related and can be used when the number of communicating objects starts to proliferate. You could implement some policy to co-ordinate the activities a more structured way within these.


Two alternatives from me: using actor model (like akka framework) or using executor to limit the parallelization. Executor is basically just a thread pool which will limit the number of thread and reuse finished threads.

0

精彩评论

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