dimanche 5 mars 2023

What are the differences between the Mediator and Command Design pattern?

The Mediator and Command design pattern are both Behavioral patterns and describe decoupling a Sender from its Receiver via an intermediate object. In case of the Mediator pattern this intermediate object is called the 'Mediator'. In case of the Command pattern this intermediate object is called the 'Command'. Their difference seems obvious in intent:

  • The Command pattern facilitates a function call in the form of an object to gain the advantages of OO.
  • The Mediator pattern extracts and centralizes complex object interaction logic.

However, looking more closely to the patterns it seems that the Command pattern is a smaller and more simpler form of a Mediator. My observations:

  • The Command pattern is unidirectional, meaning object 1 can send a message to object 2 via a Command object, but not visa versa. A new Command class would be needed to send a message from object 2 to object 1.
  • The Mediator pattern is bidirectional, meaning object 1 can send a message to object 2 via the Mediator object and visa versa.

What can be conducted from above observation is that the same goal can be achieved with the Mediator and Command pattern. Only the Command pattern provides messaging in a more distributed way, while the Mediator provides messaging in a more centralized way. This means:

  • The Command pattern complies to the Single Responsibility Principle. Each Command contains a single transaction, which has positive affect on the testability, readability and stability of the code. Testability and readability, because the problem window is small. Stability, because the impact of changing a Command is relatively small.
  • The Mediator pattern complies to the Single Responsibility Principle, but in a different way. A Mediator contains multiple transactions in a centralized place, that simplifies understanding and extendibility. Understanding, because complex interaction logic between multiple objects can be seen at a glance. Extendibility, because interaction logic can be changed in a single place, by inheriting from the Mediator base.

Are my observations correct and complete? Do these observations describe when we would prefer one pattern over the other?

(I viewed the following post: What are the differences between the Command Dispatcher and Mediator Design Pattern?. However, the post didn't fully satisfy the answer that I'm looking for. The answer given in this post doesn't elaborate extensively enough about the differences between the two patterns. On top of that, I'm not quite sure if the 'Command Dispatcher' references to the Command Design pattern.)

Aucun commentaire:

Enregistrer un commentaire