What is a pattern?
Why are patterns useful?
Our definition:
Examples: Bad (but useful) driving patterns
Design Patterns (for software developnment)
Known solutions to problems that frequently arise in software development.
Goal of most design patterns w.r.t. software development –> dependency management.
Types of design patterns (for software development)
First design pattern: Command pattern
command (in software development) ~ an object whose job is to store all the information needed to execute a particular action. See https://www.baeldung.com/java-command-pattern.
Command pattern ~ an interface, typically named Command
, with a single method, typically named Execute
.
Useful for:
How is the Command pattern useful for “undoing” commands?
Example: imagine creating an interface called Task
with a single method, execute
Create a derivative of command object for every button in the pallete.
Advantages: makes our code extensible because we can add new commands without changing existing code (Supports open-closed principle)
Components of the Command pattern
From Wikipedia:
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Four terms always associated with the command pattern are command, receiver, invoker and client. A command object knows about receiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command. The receiver object to execute these methods is also stored in the command object by aggregation. The receiver then does the work when the execute() method in command is called. An invoker object knows how to execute a command, and optionally does bookkeeping about the command execution. The invoker does not know anything about a concrete command, it knows only about the command interface. Invoker object(s), command objects and receiver objects are held by a client object, the client decides which receiver objects it assigns to the command objects, and which commands it assigns to the invoker. The client decides which commands to execute at which points. To execute a command, it passes the command object to the invoker object.
When should you use the Command pattern?