Having seen how Command pattern was used in a previous project, I can understand how it can be useful in multithreaded (parallel) programming, because Commands can be executed in different threads. When data needs to be passed between commands, the data can be stored in a shared memory and a pointer (or handle) to that data can be passed to an invoker on a differeht thread.
However, Decorator pattern seems to have the restriction that everything must happen on a single thread, because the decorator has to call the delegate directly, implying they must be on the same thread.
Is my understanding of this limitation correct? On the contrary, is it possible to run decorator on multiple threads?
What I'm trying to implement is a pipeline that processes a stream of data.
execute
method would take two arguments: a buffer for input and a buffer for output.getdata
method would call its delegate to get the result of the previous step, apply its own processing, and return the result to the caller.However after I have implemented it in both styles, I found that each has limitations that wasn't clear to me originally.
Whether you can run Decorators on any thread is implementation defined :)
If your decorators are thread safe... yes. If not: add synchronisation. This might undermine your performance.
However, in my view, it makes a lot of sense for decorators to mostly occupy themselves with the object they are decorating, and only little bits of context/state outside that. The object being decorated here, obviously should be threadsafe (or aware) in the first place, or it would have the same problem even without the decorator.
Perhaps this is what you call 'lightweight' decorators. If your decorators are heavyweight (in that they 'use the world' to do their job) there's definitely going to be synchronisation required. This may even lead to performance bottlenecks.
But fundamentally nothing precludes a (in general) decorator from being executed on any thread you want.