Search code examples
multithreadingdesign-patternsdecoratorcommand-pattern

To use multithreading, is Command pattern more useful than Decorator pattern?


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.

  • To implement as Command pattern, its execute method would take two arguments: a buffer for input and a buffer for output.
  • To implement as Decorator pattern, its 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.

  • When using the Command pattern, I can start accepting more input data by using a new buffer, while the earlier buffers are being processed by some Commands running in separate work threads. I can't seem to do this with Decorator pattern.
  • When using the Decorator pattern, the decorator can make any number of calls to its delegate and be able to combine the results into one chunk. It can also split data, by making one big request, cache it, and then returning pieces of it. When I use Command pattern with one input buffer and one output buffer, there cannot be any combination or splitting of results.

Solution

  • 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.