Day School 03 - 19 - 08 - 2023-LMS
Day School 03 - 19 - 08 - 2023-LMS
Application Development
Day School 3
2
Why Design Patterns?
• OOP Solutions
• Easy to maintain
• Efficient
Elements of Design Pattern
A Design Pattern has 4 basic parts:
1. Name
2. Problem
• What is the problem and the context where we would use this pattern?
• Under what specific conditions should this pattern be used?
3. Solution
• A description of the elements that make up the design pattern
• Emphasizes their relationships, responsibilities, and collaborations
• Not a concrete design or implementation; rather an abstract description
4. Consequences and trade-offs of application
• The pros and cons of using the pattern
• Includes impacts on reusability, portability, and extensibility
Design Pattern Template
• Name
o Describe the essence of the pattern in short, but expressive name
• Intent
o short description of pattern and its purpose
• Also Known As
o other names that people have for the pattern
• Motivation
o motivating scenario demonstrating pattern's use
• Applicability
o circumstances in which pattern applies
• Structure
o graphical representation of the pattern
• Participants
o participating classes and/or objects and their responsibilities
Design Pattern Template
• Collaborations
o how participants cooperate to carry out their responsibilities
• Consequences
o the results of application, benets, liabilities
• Implementation
o implementation pitfalls, hints, or techniques, plus any language-dependent
issues
• Sample Code
o sample implementations in java
• Known Uses
o examples drawn from existing systems
• Related Patterns
o discussion of other patterns that relate to this one
Classification to Design patterns
Design patterns differ by their complexity, level of detail and scale of applicability.
In addition, they can be categorized by their intent and divided into three groups
and they are.
7
Creational Design patterns
These design patterns are all about class instantiation or object
creation.
o Singleton Pattern
o Factory Design Pattern
o Abstract Factory Pattern
o Prototype Pattern
o Builder Pattern
o Objet Pool Pattern
8
1. Singleton Design Pattern
Intent
• Ensure a class has only one instance, and provide a global
point of access to it.
Problem
• Application needs one, and only one, instance of an
object. Additionally, lazy initialization and global access
are necessary.
Solution
• Make the class of the single instance responsible for access and
“initialization on first use”. The single instance is a private static
attribute. The accessor function is a public static method.
Structure - Singleton design pattern class diagram
11
Participants
• Static member: It gets memory only once because of
static, it contains the instance of the Singleton class.
• Private constructor: It will prevent to instantiate the
Singleton class from outside the class.
• Static factory method: This provides the global point of
access to the Singleton object and returns the instance to
the caller.
12
Singleton design pattern implementation
13
Singleton design pattern implementation
14
2. Factory Method Design Pattern
Intent
It follows the principle of ‘Define an interface or abstract class for creating an object but let the
subclasses decide which class to instantiate’
The Problem
• One of the goals of object-oriented design is to delegate responsibility among different objects.
This kind of partitioning is good since it encourages Encapsulation and Delegation.
• Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that
it must create. The Application (or framework) may know that it has to instantiate classes, but it
may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the
Application class may only know when it has to instantiate a new Object of a class, not what
kind of subclass to create.
• a class may want it's subclasses to specify the objects to be created.
• a class may delegate responsibility to one of several helper subclasses so that knowledge can be
localized to specific helper subclasses.
Applicability
Use Factory Design Pattern
• When a class doesn't know what sub-classes will be
required to create
• When a class wants that its sub-classes specify the objects
to be created.
• When the parent classes choose the creation of objects to
its sub-classes.
16
Structure – Factory method design pattern class diagram
17
Participants
• Creator - declares the interface for object creation and has
references to products to be created.
• ConcreteCreator - defines the creator interface and creates
objects independently.
• Product - declares the interface for product objects.
• ConcreteProduct - defines different concrete products.
3. Abstract Factory Design Pattern
Intent
• Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.
Problem
• If an application is to be portable, it needs to encapsulate platform dependencies.
And to provide an interface for creating these objects that allows for flexibility and
modularity in the code.
Solution
• The Abstract Factory defines a Factory Method per product. Each Factory Method
encapsulates the new operator and the concrete, platform-specific, product
classes. Each “platform” is then modeled with a Factory derived class.
Applicability
Use Abstract Factory Pattern when
• system needs to be independent of how its object are created, composed, and
represented.
• family of related objects has to be used together, then this constraint needs to be
enforced.
• you want to provide a library of objects that does not show implementations and
only reveals interfaces.
• the system needs to be configured with one of a multiple family of objects.
Structure – Abstract Factory design pattern class diagram
Exercise in LMS
• Activity 3.1 Do you agree Abstract factory design pattern is
one level higher than Factory design pattern? If yes,
Discuss why ?
22
Structural Design patterns
These design patterns are about organizing different classes and
objects to form larger structures and provide new functionality.
• Composite Pattern
• Adapter Pattern
• Proxy Pattern
• Façade Pattern
• Bridge Pattern
• Decorator Pattern
• Flyweight Pattern
23
1. Composite design pattern
Intent
• Composite pattern is used where we need to treat a group of objects in similar
way as a single object.
• Composite pattern composes objects in term of a tree structure to represent
part as well as whole hierarchy.
Problem
• solves the challenges faced when creating hierarchical tree structures to provide
clients with a uniform way to access and manipulate objects in the tree. The
composite pattern is a good choice; it is less complex in this situation to treat
primitives and composites as homogeneous.
24
Structure – Composite design pattern class diagram
25
Participants
• Component – Component declares the interface for objects in the
composition and for accessing and managing its child components. It also
implements default behavior for the interface common to all classes as
appropriate.
• Leaf – Leaf defines behavior for primitive objects in the composition. It
represents leaf objects in the composition.
• Composite – Composite stores child components and implements child
related operations in the component interface.
• Client – Client manipulates the objects in the composition through the
component interface.
26
Composite design pattern Implementation example
27
Composite design pattern Implementation
28
Composite design pattern Implementation
29
2. Adapter design pattern – Class Adapter & Object
Adapter
Intent
• Provide the interface according to client requirement
while using the services of a class with a different
interface.
• The structure of a Class Adapter uses multiple inheritance
to adapt one interface to another.
• In contrast, an Object Adapter relies on object
composition.
Applicability
Use the Adapter design pattern when
• you want to use an existing class, and its interface does not match
the one you need.
• you want to create a reusable class that cooperates with unrelated
or unforeseen classes, that is, classes that don't necessarily have
compatible interfaces.
• (object adapter only) you need to use several existing subclasses,
but it's impractical to adapt their interface by subclassing every
one. An object adapter can adapt the interface of its parent class.
Structure – Adapter design pattern class diagram
32
Participants
• Target Interface: This is the desired interface class which will be used by
the clients.
• Adapter class: This class is a wrapper class which implements the desired
target interface and modifies the specific request available from the
Adaptee class.
• Adaptee class: This is the class which is used by the Adapter class to reuse
the existing functionality and modify them for desired use.
• Client: This class will interact with the Adapter class.
33
3. Proxy design pattern
Intent
• Proxy means an object representing another object.
• This pattern provides the control for accessing the original object
Problem
• Sometimes, objects are expensive to create and initialize. It can be a
good design decision to defer the expensive operations until a time
when they are actually needed, to use a lightweight placeholder in
lieu of the expensive object. You see this in Microsoft Word where
an object has been inserted into a document, but doesn't need to
be fully loaded until edited or rendered.
Applicability / Proxy Variants
• Remote Proxy: where you represent a remote object through a
local object
• Virtual Proxy: which provides on demand creation of expensive
objects
• Protection Proxy: which controls access to the original object; and
a smart reference, also known as a smart pointer, which provides
"decorated" functionality to the proxied object (such as a smart
pointer, persisted object loader, or wrapper object for
multithreaded operations to a single-threaded object.)
Structure – Proxy design pattern class diagram
36
4. Facade design pattern
Intent
• Provide a unified interface to a set of interfaces in a subsystem. Façade defines a
higher-level interface that makes the subsystem easier to use.
Motivation
• Structuring a system into subsystems helps reduce complexity
• Subsystems are groups of classes or groups of classes and other subsystems
• The interface exposed by the classes in a subsystem or set of subsystems can
become quite complex.
• One way to reduce this complexity is to introduce a façade object that provides a
single, simplified interface to the more general facilities of a subsystem.
37
4. Facade design pattern
Applicability
Use the Facade pattern:
• To provide a simple interface to a complex subsystem. This interface
is good enough for most clients; more sophisticated clients can look
beyond the facade.
• To decouple the classes of the subsystem from its clients and other
subsystems, thereby promoting subsystem independence and
portability
38
Exercise in LMS
• Activity 3.2 - Differences between different Structural
Design Patterns
39
Behavioral Design patterns
Behavioral patterns are about identifying common communication patterns
between objects and realize these patterns.
• Observer Pattern
• Template Pattern
• Strategy Pattern
• Iterator Pattern
• Command Pattern
• Interpreter Pattern
• Mediator Pattern
• State Pattern
• Visitor Pattern
40
1. Observer design pattern
Intent
• Define a one-to-many dependency between objects so
that when one object changes state, all its dependents are
notified and updated automatically
• The need to maintain consistency between related objects
without making classes tightly coupled
Applicability
Use the Observer pattern in any of the following situations:
• When an abstraction has two aspects, one dependent on the other.
• Encapsulating these aspects in separate objects lets you vary and reuse
them independently.
• When a change to one object requires changing others
• When an object should be able to notify other objects without making
assumptions about those objects
43
Structure – Observer design pattern class diagram
44
Participants
Subject
• Keeps track of its observers
• Provides an interface for attaching and detaching Observer objects
Observer
• Defines an interface for update notification
ConcreteSubject
• The object being observed
• Stores state of interest to ConcreteObserver objects
• Sends a notification to its observers when its state changes
ConcreteObserver
• The observing object
• Stores state that should stay consistent with the subject's
• Implements the Observer update interface to keep its state consistent with the subject
Observer design pattern Implementation example
46
Observer design pattern Implementation example
47
Observer design pattern Implementation example
48
Observer design pattern Implementation example
49
Observer design pattern Implementation example
50
2. Template design pattern
Intent
• Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine
certain steps of an algorithm without changing the algorithm's
structure.
Motivation
• Sometimes you want to specify the order of operations that a
method uses, but allow subclasses to provide their own
implementations of some of these operations
Applicability / Problem
Use the Template Method pattern:
• To implement the invariant parts of an algorithm once and leave it
up to subclasses to implement the behavior that can vary
• To localize common behavior among subclasses and place it in a
common class (in this case, a superclass) to avoid code duplication.
This is a classic example of ”code refactoring.”
• To control how subclasses extend superclass operations. You can
define a template method that calls "hook" operations at specific
points, thereby permitting extensions only at those points.
Structure – Template design pattern class diagram
53
Template design pattern Implementation example
Template design pattern Implementation example
The OpenDocument() method might look like this:
public void OpenDocument (String name) {
if (!CanOpenDocument(name)) { return; }
Document doc = DoCreateDocument();
if (doc !!= null) {
docs.AddDocument(doc);
AboutToOpenDocument(doc);
doc.Open();
doc.DoRead();
}
}
Template design pattern Implementation example
Intent
• We create objects which represent various strategies and a context object whose
behavior varies as per its strategy object. The strategy object changes the executing
algorithm of the context object.
• Class behavior or its algorithm can be changed at run time.
Problem
• Often in software development, actions an object must take depend on the context in
which they are performed. For example, a text-rendering engine may lay out text as
plaintext in one case, rich text in another, and as cells in a spreadsheet in yet another.
While the activity is the same, composition, the algorithm used varies. The Strategy
behavioral design pattern is useful in that it "define[s] a family of algorithms,
encapsulate[s] each one, and make[s] them interchangeable. Strategy lets the
algorithm vary independently from the clients that use it." (GOF).
Structure – Strategy design pattern class diagram
Participants
• Context defines an interface for configuring strategies and
maintains a reference to Strategy.
• Strategy defines an interface for all interchangeable algorithms
• Concrete Strategies defines different algorithms.
4. Iterator design pattern
Iterator pattern is very commonly used design pattern in Java and .Net
programming environment. This pattern is used to get a way to access the
elements of a collection object in sequential manner without any need to
know its underlying representation.
Watch : https://www.youtube.com/watch?v=wqD4fOiGep4
60
Structure – Iterator design pattern class diagram
61
-END-
62