0% found this document useful (0 votes)
6 views115 pages

Design Patterns v3 Amal Introduction Creational Patterns

The document provides an overview of design patterns in software development, including their importance, types, and specific patterns like Singleton, Factory Method, and Abstract Factory. It emphasizes the benefits of design patterns in creating reusable and efficient software solutions while reducing trial and error in design. Additionally, it outlines the structure and key components of design patterns, including their applicability and consequences.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views115 pages

Design Patterns v3 Amal Introduction Creational Patterns

The document provides an overview of design patterns in software development, including their importance, types, and specific patterns like Singleton, Factory Method, and Abstract Factory. It emphasizes the benefits of design patterns in creating reusable and efficient software solutions while reducing trial and error in design. Additionally, it outlines the structure and key components of design patterns, including their applicability and consequences.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

Design Patterns

A good class is a lot like an iceberg: seven-


eights is under water, and you can see only the
one-eight that’s above the surface.

Tempus
McConnell
Module Topics (Cont’d)

 Introduction to Design Patterns


 Creational Patterns
 Structural Patterns
 Behavioral Patterns
Design patterns

• Architectural Design Patterns (will be covered after the


mid-term exam)
• Software Design Patterns (will be covered till the mid-
term exam)
Architectural Design Patterns (will be covered after the
mid-term exam)
Architectural Patterns
So, what are Software Design Patterns?

Watch Video!
Facing Design Problems
 A hard-to-do assignment for the architect/designer to design
reusable software!
Requires: (i) good understanding of the problem, and proper software;
(ii) flexible, modular and robust software design

 Designing SW is driven by trial and error manner


 It is done correctly, so what?
designing a solution is not identical each time this is done; they exhibit
some recurring characteristics

 What’s the impact of Standardizing, describing, or codifying


SW designs? No more trial and error experiments; Better and faster
development of software
What ancient said about similar problems?
 Christopher Alexander said: "Each pattern describes a
problem which occurs over and over again in our
environment, and then describes the core of the solution to
that problem, in such a way that you can use this solution a
million times over, without ever doing it the same way
twice“ 1977
 Different engineering discipline (construction). Building
blocks are walls, doors, etc. -> classes, objects, interfaces
 Patterns provide the best solution of a problem within a
specific context
Defining Design Pattern
Design Pattern

 is the act of providing a solution to a commonly repeated


software problem in a specific context that:
o describes a repeating software designing issue
o should overcome the barriers of programming languages’
differences
o identifies the roles of OO concepts in the solution to a problem
o Patterns are not a copy-&-paste code or designs; nevertheless
must be instantiated from the situation and applied to solve it
Example
 Frequent Problem: Consider that we need to perform
read and write operations over an aggregate (collection)
without accessing its representation directly. This
should be done in a sequential manner.

 Design Pattern Solution: In order to introduce a


solution for such frequent problem, an Iterator Pattern
was introduced.
Iterator Pattern will be discussed later.
Design Patterns Importance
in Design Problem Solving
Patterns Advantages

 From a designing perspective, patterns are


considered a common term.
 Software developers are able to use separate the design
from the implementation; increase designing speed
 Share experienced designers’ experience.
 Less documentation
 More design understanding
Describing a Design
Pattern
Gang of four
Pattern Distillation
 A pattern has four important pillars:
o Pattern Name
o Problem: the situations that should apply the pattern and the context
of this pattern. Problem can also define any preconditions or constrains
while implementing the pattern.
o Solution: an abstract description of how classes and objects can solve
this particular problem
o the solution avail relationship among design elements and their
responsibilities and collaboration.
o Consequences: Each single choice has its own cost and its drawbacks. This
must be known to be able to measure the trade-off between the patterns. This
includes its impact on a system's quality attributes QA
Pattern Distillation (Cont’d)
 Each pattern is discussed from 13 aspects to form a structured template
for learning, comparing , and using different patterns.
 13 aspects:
1. Pattern Name and Classification: a good name is vital, because it will
become part of your design vocabulary
2. Intent: can be acquired if the following questions are answered:
• What problem can this pattern solve?
• What does the pattern do?
3. Also Known As: Synonyms
4. Motivation: a scenario that shows a design problem and how the class
structures in the pattern solve the problem
Pattern Distillation (Cont’d)
 13 aspects (Cont’d):
5. Applicability: When the pattern is applicable? And When it’s not?
6. Structure: Notation describes the used classes in this pattern (UML)
7. Participants: Mentioning and describing the responsibilities of the classes
participating in the pattern
8. Collaborations: Describing the collaboration between the different
classes to how to achieve their responsibilities
Pattern Distillation (Cont’d)
 13 aspects (Cont’d):
9. Consequences: describing how the pattern overcame the problem?
And what trade-offs after selecting this pattern?
10.Implementation: what techniques are better recommended? show
language barriers-if any
11.Sample Code: provided code will be introduced in Java/C#
12.Known Uses: show real-world cases
13.Related Patterns: which patterns are almost close to this pattern?
Three Design Pattern Axes

 Design patterns vary in their granularity and level of abstraction.


Because there are many design patterns, we need a way to organize
them.

 Classifying design patterns can refer to families of related patterns.


Patterns are categorized for their purposes.

 There are three main categorical purposes:


o Creational: concern the process of object creation
o Structural: deal with the composition of classes or objects
o Behavioral: characterize the ways in which classes or objects interact and
distribute responsibility
Creational Patterns
Creational Patterns Discussion

 Creational patterns abstract the object instantiation process.


 Creational patterns become essential as systems improved to
depend more on composition than inheritance. This pushes to
find a more than the simple form of instantiating objects from
classes
 There are two recurring themes in these patterns.
o Firstly, they encapsulate all the elements (operation and data) which
concrete classes in the system uses.
o Secondly, they hide how instances of these classes are created and
put together.
Creational Patterns

 Singleton
 Factory Method
 Abstract Factory
 Builder
 Prototype
Singleton

Watch the
Video!
Singleton

 Intent: Ensures a class only has one instance, and provides a


global point of access to it.
 Also Known As: N/A
 Motivation:
 When a class’s situation is in need to have one and only one object
instantiated in the application’s life-time. Let’s say we talk about file
system in operating system, it’s obviously that OS needs one file
system object. Other example is the service that manages any
number of printers connected to an OS, just one service is needed.
Implementation
Nothing in this code prevents two threads from
accessing this piece of code at the same time
Now, even if the instance was created, every thread has to wait
before returning it
Every time we
access this
variable
(instance), we
need to read it
directly from the
main memory as
it can’t be cached
• In this code
snippet, even
if the variable
is already
initialized, we
have to fetch
it twice

• How to
avoid this
and access
the memory
only once?
Singleton (Cont’d)
 Motivation (Cont’d): An idea might come up to your mind by
saying:
“Hey, it’s static class!; the solution of the one-instantiated-object”.
The static class has a limitations like, e.g.:
 it’s rigid (it isn’t flexible, it can’t be extended, overridden,… i.e. No
Inheritance),
 there is no object so tracking the state is a nightmare. Therefore, static
limitations is a motivation to a new solution.
 The solution simply resides in forcing the class to track its first object
by itself. The class can ensure that no other instance can be created
(by intercepting requests to create new objects), and it can provide a
way to access the instance. This is the Singleton pattern.
Singleton (Cont’d)
 Applicability:
o There must be exactly one instance of a class, and it must be
accessible to clients from a well-known access point.
o When the sole instance should be extensible by subclassing, then
clients should be able to use an extended instance without modifying
their code.
Singleton (Cont’d)
 Structure:

return instance
Singleton (Cont’d)
 Participants:
• Defines Instance class interface which is responsible for accessing the
unique instance
• May instantiate its instance by itself
 Collaborations: clients can access singleton class through
Instance operation (class interface)
Singleton (Cont’d)
 Consequences:
o Controls the access to the only instance
o Avoids global variables in namespaces which reduces it.
o Allows inherence which permits run-time assignment of the subclasses
to the superclass
o Allows a two, or three, or any limited specific number of objects by
almost using the same technique.
Singleton (Cont’d)
 Implementation:
o Firstly, we need to hide the singleton's constructor in order to block
instantiating the any objects from it. This will be done by marking the
constructor with a protect access modifier. This in turn will produce
compilation-time error if any object is instantiated through the
constructor.
o In order to avail the initiation of the constructor or obtaining the soul
instance, a static method have to be provided. This static method
would have access to the protected constructor and it can be accessed
from the outside. In addition, this method will have an exclusive
access to a private singleton member which is an instance of the
singleton class.
Singleton (Cont’d)
 Implementation (Cont’d):
o Inheriting Singleton class has an issue of defining the unique instance
that clients will be able to use it.
• A possible solution is initializing the singleton instance with one of the subclasses
based on a variable to determine which class will be instantiated. This simply can
be implemented in the Instance operation of the singleton class.
• Another solution is to take the Instance operation from the parent singleton to
the subclass, but any client of the parent singleton will not be able to know the
instance. The link approach fixes the choice of singleton class at link-time, which
makes it hard to choose the parent singleton class at run-time.
• A more flexible way, is to create the a registry of singleton that captures the
instances by classes’ names, instead of having the Instance operation define the
set of possible classes with a variable. When Instance operation needs a
singleton it looks up the registry by the singleton class name.
Singleton (Cont’d): C#
 Source Code:
public class mySingleton {
//shared members
private static mySingleton _instance;
public static mySingleton getInstance() {
if(_instance == null)
_instance = new mySingelton();
return _instance;
}
//instance members
protected mySingleton() {
//public instantiation disallowed
}
//other instance members
//...
}
Singleton (Cont’d)
 Source Code(Cont’d):
public class Program {
static void Main(string[] args) {
mySingleton Singleton1 = SingletonSample.getInstance();
}
}
Singleton (Cont’d)
 Known Uses:
o For “Abstract Factory Design” pattern only one instance of ConcreteFactory
class is needed per product family. “Singleton Design Pattern” is applied
o Single configuration for an application.
 Related Patterns:
o Abstract Factory
o Builder
o Prototype
Exercise 3.2
Singleton Exercise

 Consider an application that depends on a set of configurations.


Configurations is considered as a class, that couldn’t be
instantiated twice.
 Draw a UML class Diagram to illustrate the case
 Write Java source code to implement this request.
Exercise 3.2 Solution

Configuration
UML Class Diagram

private static uniqueInstance

public static Instance ()


private Configuration()
Exercise 3.2 Solution (Cont’d): In C#
• H.W: Extend and write
 Source Code: this code in Java by
public class Configuration { considering:
• Multithreading
private static Configuration _instance; (synchronized
public static Configuration Instance() { keyword)
if(_instance == null) • Incomplete instance
_instance = new Configuration (); initiation (volatile
return _instance; keyword)
} • Method performance
protected Configuration () {} (introduce a local
variable inside the
}
Instance method)
Singleton (Cont’d)
 Source Code(Cont’d):
public class Program {
static void Main(string[] args) {
Configuration Singleton1 = Configuration.Instance();
Configuration Singleton2 = Configuration.Instance();
// We will find that both Sigleton1 and Singleton2 are
//shallow cloned i.e. both have the same address
}
}
Creational Patterns

 Singleton
 Factory Method
 Abstract Factory
 Builder
 Prototype
Simple Factory Idiom and Factory Method Pattern

Watch Video!
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom

• What is the
problem with
this code?
• It violates the
single
responsibility
principle and
the open-
closed
principle
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom
Simple Factory Idiom

Abstract
Client Factory product

Concrete
products
Simple Factory Idiom
Simple Factory Idiom

violates the
open–closed
principle (OCP)
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern
Factory Method pattern: usage
Factory Method pattern

Burger
Restaurant

Abstract
Factory
method

BeefBurgerRetaurant

BeefBurger

VeggieBurger
VeggieBurgerRetaurant
When to use the Factory Method Patten?
Assume that your business expanded, and you opened a
new Italian Restaurant?

• This code
becomes open
for
modifications,
violating the
open-closed
principle
• Any other
problems in this
code?
Factory Method pattern
The Abstract Factory Pattern
Abstract Factory Pattern

Watch Video!
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern
The Abstract Factory Pattern: usage
MsiManufacturer
MsiGpu MsiMonitor

Company
Gpu Monitor

AsusGpu AsusMonitor

AsusManufacturer
Abstract Factory

 Intent: Provide an interface for creating families of related or


dependent objects without specifying their concrete classes.
 Also Known As: Kit
 Motivation: Consider a Work Item Tracking (WIT) system, this
system supports different Process Models, like, Agile, CMMI,
Scrum, etc. Work Items (WI) can be Requirement, Bug, Test
Case, etc. We need to instantiate the WIs of specific process
model. If the WIs is modified or extended this means that the
instantiation process becomes harder.
Abstract Factory (Cont’d)

 Motivation (Cont’d): We can solve this problem by creating


an abstract class in which it contains a class interface for each
type of WIs to instantiate it. In addition, for each group –
Process Model, of WIs an abstract class is created and this
abstract class is considered as a superclass for a set of concrete
classes, each of them implements the WI logic by itself.
Client(or Team Member in this case) can call the operations of
each process model but without being able to know how it’s
implemented. Therefore, the client stays independent of the WI
type.
Abstract Factory (Cont’d)

 Applicability: Abstract Factory should be used when:


o Independency of a product is required from the process of
creation, composition, and representation of its product
o system should be configured with one of multiple families of
products.
o family of related product objects is designed to be used
together, and you need to enforce this constraint.
o you want to provide a class library of products, and you want
to reveal just their interfaces, not their implementations.
Abstract Factory Structure
Abstract Factory (Cont’d)

 Participants:
o AbstractFactory: declares an interface for operations that
create abstract product objects. (Consider it the protocol of a
factory making products)
o ConcreteFactory (RequirementConcreteFactory and
BugConcreteFactory ): implements the operations to create
concrete product objects. (Consider it the order of creating
specific products)
Abstract Factory (Cont’d)

 Participants (Cont’d):
o AbstractProduct (AgileProcessModel and CMMIProcessModel):
declares an interface for a type of product object.
o ConcreteProduct (AgileRequirement, CMMIRequirement,
CMMIRequirement, CMMIBug):
• defines a product object to be created by the corresponding concrete
factory.
• implements the AbstractProduct interface.
o Client (TeamMember): uses only interfaces declared by
AbstractFactory and AbstractProduct classes.
Abstract Factory (Cont’d)

 Collaboration:
o AbstractFactory defers creation of product objects to its
ConcreteFactory subclass.
o ConcreteFactory instantiates the ConcreteProduct class’s
object.
Abstract Factory (Cont’d)

 Consequences:
o Concrete classes isolation
o Ease of selection between product families
o Promotes consistency among products
Abstract Factory (Cont’d)

 Implementation:
o AbstractFactory declares creating the abstract products using the class
interface only. However, the ConcreteProduct has the implementation for
each product independently. In order to make the abstract factory create
the products instance, a ConcreteFactory class implements the class
interface in the AbstractFactory class. The concreteFactory class
instantiate the objects of a products family from each ConcreteProduct
class.
• In order to create a new product family, a new ConcreteFamily class is created.
• The class interface in the AbstractFactory class and its implementation in the
ConcreteFactory class which instantiate the ConcreteProduct ’s objects is a design
Pattern called “Abstract Method”
Abstract Factory (Cont’d)

 Implementation:
o Only one instance of ConcreteFactory class is needed per
product family. This typically provided by “Singleton Design
Pattern”.
o If many product families are expected, the ConcreteFactory can
be implemented using the “Prototype Design Pattern”. We are
not going to discuss it in this presentation. The ConcreteFactory
is initialized with a prototypical instance of each product in the
family, and it creates a new product by cloning its prototype.
The Prototype-based approach eliminates the need for a new
concrete factory class for each new product family.
Abstract Factory (Cont’d) in C# (Write the same code in
Java)
 Sample Code:
abstract class AgileProcessModel { } //AbstractProductA
abstract class CMMIProcessModel { } //AbstractProductB
class AgileRequirement : AgileProcessModel { } //ProductA1
class AgileBug : AgileProcessModel { } //ProductA2
class CMMIRequirement : CMMIProcessModel { } // ProductB1
class CMMIBug : CMMIProcessModel { } // ProductB2
Abstract Factory (Cont’d)

 Sample Code (Cont’d) :


abstract class AbstractFactory
{
public abstract AgileProcessModel CreateAgile(); //Instantiate ProductA
public abstract CMMIProcessModel CreateCMMI(); //Instantiate ProductB
}
Abstract Factory (Cont’d)

 Sample Code (Cont’d) :


class RequirementConcreteFactory : AbstractFactory //ProductFamily1
{
public override AgileProcessModel CreateAgile()
{ return new AgileRequirement (); }

public override CMMIProcessModel CreateCMMI()


{ return new CMMIRequirement (); }
}
Abstract Factory (Cont’d)
 Sample Code (Cont’d) :
class BugConcreteFactory : AbstractFactory //ProductFamily2
{
public override AgileProcessModel CreateAgile()
{ return new AgileBug (); }

public override CMMIProcessModel CreateCMMI()


{ return new CMMIBug (); }
}
Abstract Factory (Cont’d)
 Sample Code (Cont’d) :
class TeamMember {
// client code that does not need to be changed
private static void CreateAgile (AbstractFactory f){
AgileProcessModel d = f.CreateAgile();
}
// client code that does not need to be changed
private static void CreateCMMI (AbstractFactory f){
CMMIProcessModel d = f.CreateCMMI();
}

AbstractFactory Req= new RequirementConcreteFactory();


CreateAgile(Req);
CreateCMMI(Req);

AbstractFactory Bug= new BugConcreteFactory();


CreateAgile(Bug);
CreateCMMI(Bug);
}
Abstract Factory (Cont’d)
 Known Uses:
o Generating look-and-feel-specific user interface object as this pattern can
help generating different composition objects depending on the chosen
layout. Horizontal layout may require different composition objects
depending on the document's orientation (portrait or landscape).
 Related Patterns:
o ConcreteFactory classes always implemented as Sigleton
o AbstractFactory class has class interface implemented as FactoryMethod,
but it can be implemented as Prototype
Thank you for
your attention.

Tempus

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy