0% found this document useful (0 votes)
0 views

Lecture 11 Design Pattern

The document discusses design patterns in software development, defining them as standard solutions to common problems and highlighting their benefits, such as improved communication and documentation. It categorizes design patterns into three types: Creational, Structural, and Behavioral, and provides examples of each type, including Factory Method, Adapter, and Command patterns. Additionally, it emphasizes the advantages of using the Command pattern, such as adherence to design principles and support for undo/redo functionality.

Uploaded by

aoe7289
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lecture 11 Design Pattern

The document discusses design patterns in software development, defining them as standard solutions to common problems and highlighting their benefits, such as improved communication and documentation. It categorizes design patterns into three types: Creational, Structural, and Behavioral, and provides examples of each type, including Factory Method, Adapter, and Command patterns. Additionally, it emphasizes the advantages of using the Command pattern, such as adherence to design principles and support for undo/redo functionality.

Uploaded by

aoe7289
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Object-Oriented

Programming
IT069IU
Lecture 11
Design Pattern

Dr. Huynh Tan Quoc


Design patterns
Design pattern:
A standard solution to a common software problem in a context.
• describes a recurring software structure or idiom
• is abstract from any particular programming language
• identifies classes and their roles in the solution to a problem

in 1990 a group called the Gang of Four or "GoF"


(Gamma, Helm, Johnson, Vlissides) compile a
catalog of design patterns
• 1995 book Design Patterns:
Elements of Reusable Object-Oriented
Software is a classic of the field

References:
• https://refactoring.guru/design-patterns
• https://www.geeksforgeeks.org/software-design-patterns/
Benefits of using patterns

• Patterns give a design common vocabulary for software design:


• Allows engineers to abstract a problem and talk about that abstraction in isolation from its
implementation.

• A culture; domain-specific patterns increase design speed.

• Capture expertise and allow it to be communicated:


• Promotes design reuse and avoid mistakes.

• Makes it easier for other developers to understand a system.

• Improve documentation (less is needed):


• Improve understandability (patterns are described well, once).
Types of Software Design Patterns

There are three types of Design Patterns:


Creational Design Pattern
Structural Design Pattern
Behavioral Design Pattern
Creational Design Patterns

1. Factory Method Design Pattern


The Factory Method pattern is used to create objects without specifying the exact
class of object that will be created. This pattern is useful when you need to decouple
the creation of an object from its implementation.
2. Abstract Factory Method Design Pattern
Abstract Factory pattern is almost similar to Factory Pattern and is considered as
another layer of abstraction over factory pattern. Abstract Factory patterns work
around a super-factory which creates other factories.
3. Singleton Method Design Pattern
The Singleton method or Singleton Design pattern is one of the simplest design
patterns. It ensures a class only has one instance, and provides a global point of
access to it.
Creational Design Patterns

4. Prototype Method Design Pattern


Prototype allows us to hide the complexity of making new instances from the
client. The concept is to copy an existing object rather than creating a new instance
from scratch, something that may include costly operations. The existing object acts
as a prototype and contains the state of the object.
5. Builder Method Design Pattern
Builder pattern aims to “Separate the construction of a complex object from its
representation so that the same construction process can create different
representations.” It is used to construct a complex object step by step and the final
step will return the object.
Structural Design Patterns

1. Adapter Method Design Pattern


The adapter pattern convert the interface of a class into another interface clients
expect. Adapter lets classes work together that couldn’t otherwise because of
incompatible interfaces.
2. Bridge Method Design Pattern
The bridge pattern allows the Abstraction and the Implementation to be developed
independently and the client code can access only the Abstraction part without being
concerned about the Implementation part.
3. Composite Method Design Pattern
Composite pattern is a partitioning design pattern and describes a group of objects
that is treated the same way as a single instance of the same type of object. The intent
Structural Design Patterns

4. Decorator Method Design Pattern


It allows us to dynamically add functionality and behavior to an object without
affecting the behavior of other existing objects within the same class. We use
inheritance to extend the behavior of the class. This takes place at compile-time, and
all the instances of that class get the extended behavior.
5. Facade Method Design Pattern
Facade Method Design Pattern provides a unified interface to a set of interfaces in a
subsystem. Facade defines a high-level interface that makes the subsystem easier to
use.
Structural Design Patterns

6. Flyweight Method Design Pattern


This pattern provides ways to decrease object count thus improving application
required objects structure. Flyweight pattern is used when we need to create a large
number of similar objects.
7. Proxy Method Design Pattern
Proxy means ‘in place of’, representing’ or ‘in place of’ or ‘on behalf of’ are literal
meanings of proxy and that directly explains Proxy Design Pattern. Proxies are also
called surrogates, handles, and wrappers. They are closely related in structure, but
not purpose, to Adapters and Decorators.
Behavioral Design Patterns

1. Chain Of Responsibility Method Design Pattern


Chain of responsibility pattern is used to achieve loose coupling in software design
where a request from the client is passed to a chain of objects to process them. Later,
the object in the chain will decide themselves who will be processing the request and
whether the request is required to be sent to the next object in the chain or not.
2. Command Method Design Pattern
The Command Pattern is a behavioral design pattern that turns a request into a stand-
alone object, containing all the information about the request. This object can be
passed around, stored, and executed at a later time
3. Interpreter Method Design Pattern
Interpreter pattern is used to defines a grammatical representation for a language and
provides an interpreter to deal with this grammar.
Behavioral Design Patterns

4. Mediator Method Design Pattern


It enables decoupling of objects by introducing a layer in between so that the
interaction between objects happen via the layer.
5. Memento Method Design Patterns
It is used to restore state of an object to a previous state. As your application is
progressing, you may want to save checkpoints in your application and restore back to
those checkpoints later. Intent of Memento Design pattern is without violating
encapsulation, capture and externalize an object’s internal state so that the object can
be restored to this state later.
6. Observer Method Design Pattern
It defines a one-to-many dependency between objects, so that when one object (the
subject) changes its state, all its dependents (observers) are notified and updated
Behavioral Design Patterns

7. State Method Design Pattern


A state design pattern is used when an Object changes its behavior based on its
internal state. If we have to change the behavior of an object based on its state, we can
have a state variable in the Object and use the if-else condition block to perform
different actions based on the state.
8. Strategy Method Design Pattern
The Strategy Design Pattern allows the behavior of an object to be selected at runtime.
It is one of the Gang of Four (GoF) design patterns, which are widely used in object-
oriented programming. The Strategy pattern is based on the idea of encapsulating a
family of algorithms into separate classes that implement a common interface.
Behavioral Design Patterns

9. Template Method Design Pattern


Template method design pattern is to define an algorithm as a skeleton of operations
and leave the details to be implemented by the child classes. The overall structure and
sequence of the algorithm are preserved by the parent class.
10. Visitor Method Design Pattern
It is used when we have to perform an operation on a group of similar kind of Objects.
With the help of visitor pattern, we can move the operational logic from the objects to
another class.
Behavioral Design Patterns
Command Pattern
Command is a behavioral design pattern that turns a request into a stand-
alone object that contains all information about the request. This
transformation lets you pass requests as a method arguments, delay or queue
a request’s execution, and support undoable operations.

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

aClient : Client aCommand : anInvoker : aReceiver:


ConcreteCommand Invoker

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

second type is restricted to only accept "String" values.


Practice Final Exam
Consider the following UML design,
•Shape is an abstract class for Square and RightTriangle classes with an abstract method getArea()
•Suppose that:
+ The getArea() method of the Square class is defined by height * width
+ The getArea() method of the RightTriangle class is defined by 0.5 * height * width
a) Explain why the class Shape must be an abstract class?
b) Explain why the getArea() method must be an abstract method?
c) Based on the provided UML design, write code for these classes
Practice Final Exam
Using the following Java Code.
a. Explain why the design violates the Single Responsibility Principle
b. Redesign (by drawing a new UML Model) to make it conform with the Single Responsibility Principle
public class Customer {
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and setters for name, and email
public void save() {
// Code to save the customer to a database
}
public void sendEmail(String message) {
// Code to send an email to the customer
}
public void delete() {
// Code to delete the customer from the database
}
public void printReport() {
// Code to generate and print a report about the customer
}
}
Practice Final Exam
Command pattern (its structure and its collaborations are given below).
public class User {
...
public void SendEmail(string message) { /*... */ }
public void ShowInfo(){ /* ... */ }
}

public class GUI {


private ArrayList<User> users;
public GUI() { users = new ArrayList<Users>(); }

public void onMenuItem1_Click() {


for (user : users)
user.SendEmail("Happy New Year");
}

public void onMenuItem2_Click() {


for (user : users)
user.ShowInfo();
}
}

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

Collaborations in an implementation of Command pattern

You might also like