Mid GoF Patterns

Composite Commands:?

  • You can combine multiple commands into a composite command. For

example, if the user performs a series of actions (like adding text, changing

fonts, and changing colors), you can encapsulate all of those actions into a

single composite command that can be undone in one step.

Real-Time Use Case Example:

The Command Pattern is often used in:

  • Text Editors: For implementing undo/redo functionality and user interactions.
  • Transaction Systems: Where each action can be encapsulated as a command, and

the entire system can be undone or redone.

  • GUI Frameworks: Buttons, sliders, and menu items can be mapped to commands,

allowing for consistent handling of actions across the UI.

  • Gaming Applications: Where player actions (e.g., moving, shooting) can be

encapsulated as commands and undone when necessary.

Follow:

Visual Diagram:

Here's a simple visual diagram to understand the Command Pattern:

+-----------------+ +---------------------+

+------------------+

| TextEditor | ---> | AddTextCommand | ---> |

Document |

| (Invoker) | | (Concrete Command) | |

(Receiver) |

+-----------------+ +---------------------+

+------------------+

| |

+-----------+

+-------------------+

| Undo | |

AddText / RemoveText |

+-----------+

+-------------------+

The Command Pattern provides a flexible and scalable way to handle requests in

object-oriented systems, especially when you need to manage complex workflows,

implement undo/redo functionality, or decouple senders from receivers.

Composite Pattern: Real-Time Example - Building a File System

Scenario:

The Composite Pattern is used when you need to treat individual objects and compositions

of objects uniformly. This is particularly useful when you have a hierarchical structure, like a

file system, where files and directories can be treated in a similar manner.

In a file system:

  • Files are the individual objects (leaves).

Follow:

  • Directories are composite objects that can contain files or other directories

(children).

This pattern helps to simplify the management of hierarchical structures, making it easier to

handle both individual items and collections of items in a unified way.

Code Explanation:

More from Design Patterns in C#

All questions for this course