Lecture 11 Design Pattern
Lecture 11 Design Pattern
Programming
IT069IU
Lecture 11
Design Pattern
References:
• https://refactoring.guru/design-patterns
• https://www.geeksforgeeks.org/software-design-patterns/
Benefits of using patterns
Class Diagram
14
Behavioral Design Patterns
Command Pattern
Participants
• Command: Declares an interface for executing an operation.
• ConcreteCommand
• Defines a binding between a Receiver object and an action.
• Implements execute() by invoking a corresponding operation on Receiver.
Client (Application): Creates a Command object and sets its Receiver.
Invoker: Asks the Command to carry out a request.
Receiver: Knows how to perform the operation associated with a request.
Can be any class.
Collaborations
Creates a ConcreteCommand object and sets its Receiver.
An Invoker stores the ConcreteCommand.
Invoker calls execute() on command.
ConcreteCommand invokes operation on its receiver.
15
Behavioral Design Patterns
Command Pattern
Sequence Diagram
create( aReceiver )
store( aCommand )
execute()
action()
16
Example
Command Pattern
17
Behavioral Design Patterns
Advantages Command Pattern
1.Single Responsibility Principle (SRP):Each command class encapsulates a single
action or operation, adhering to the SRP.
2.Open/Closed Principle (OCP):The Command Pattern allows for the addition of new
commands without modifying existing client code.
3. Encapsulation:Commands encapsulate both the action to be performed and any
necessary parameters or context required for that action.
4.Separation of Concerns:By encapsulating commands separately from their invokers
(e.g., GUI elements, remote controls), the Command Pattern promotes a clear
separation of concerns.
5.Decoupling:The Command Pattern decouples the sender of a request from the
receiver, allowing for more flexible and loosely coupled systems.
6.Undo/Redo Functionality:The Command Pattern facilitates the implementation of
undo/redo functionality by storing command objects in a history list.
7.Composite Pattern (if applicable):In some implementations, the Command Pattern
can be combined with the Composite Pattern to create complex command hierarchies.
8.Behavioral Design Patterns:The Command Pattern is often used in conjunction with
other behavioral design patterns, such as Observer, Memento, and Strategy.
Practice Final Exam
Give an example of a generic class in Java that takes two different input parameter
types, where the first type is restricted to only accept "Number" values; and the
a. Which classes of the above code correspond to the Client class (5 marks) and the Receiver class (5
marks) of the Command pattern.
Practice Final Exam
b. Write two classes that implement the Command interface and have an Execute
method corresponding to the onMenuItem1_Click and onMenuItem2_Click functions,
respectively
c. Rewrite the GUI class to apply the Command pattern
Practice Final Exam