Search code examples
design-patternscompositecommand-pattern

I would like to know the relationship between Command pattern and Composite pattern


I am a graduate student at the department of computer science and engineering, but my undergraduate major was the industrial and management engineering. So I am sometimes confused about software engineering.

By GoF, at the chapter of the command pattern, the relation with the command pattern and the composite pattern is that composite pattern can be used to implement MacroCommands.

I thought for storing the bunch of commands, the composite pattern can be used.

But I didn't understand precisely.

My professor who teaches me about the design pattern, said the macro which is the bunch of commands, is also a command. It implies that relationship is the composite pattern.

I might be not sure whether I understand that perfectly or not.

I would like to make it sure that I understand right and his explanation is right.

Thank you for your help in advance.


Solution

  • Using the Composite pattern to represent a group of Commands, or a MacroCommand, allows whatever processes the Commands to use them via a uniform interface, regardless of their underlying type.

    Yes, the MacroCommand can be a Command itself, whilst also being a Composite that contains a number of other Commands. Assuming the use of an ICommand interface that has an Execute() method, the MacroCommand's Execute() method would iterate over the Composite structure, calling each node's Execute() method in turn.

    This is worth a read as it describes a Command Processor pattern that builds on the orignal Command pattern. It mentions the notion of a MacroCommand and its use of the Composite pattern.