SlideShare une entreprise Scribd logo
1  sur  73
CPIT-252
DESIGN PATTERNS
Teacher: Dr. Asma Cherif
Office room: 144S
email: acherif@kau.edu.sa
IT dept.
Course Coordinator: Dr. Asma Cherif
1
REFERENCES
Many resources have been used to build this course, if you notice any missing reference please
contact me at acherif@kau.edu.sa
• Roger S. Pressman, "Software Engineering: A Practitioner’s Approach", McGraw-Hill
Science/Engineering/Math; 7 edition (2010)
• GoF book
• Laurent Audibert (developpez.com)
• Dr. Birgit Demuth (OCL)
• Dr. K.M Anderson
• Head First Collection
• Software engineering, Ian Sommerville, ch2- quality management
• www.newthinktank.com
• https://sourcemaking.com
• Derek Banas youtube channel
2
CREATIONAL
PATTERNS
Creational Patterns
Creational
Patterns
Singleton
Factory
Method
BuilderPrototype
Abstract
Factory
4
FACTORY METHOD DESIGN
PATTERN
Class Creational
Known as Virtual Constructor
5
Factory Method Pattern
• Factory pattern is one of the most used design patterns in Java.
• Provides one of the best ways to create objects related with
inheritance relationship (of same type)
• Allows to create objects without exposing the creation logic to the
client and refer to newly created object using a common interface.
6
Factory Method: Intent
Define an interface for creating an object but let subclasses decide
which class to instantiate.
7
Factory Method: general structure
Product
ConcreteProduct
Factory
+FactoryMethod():Product
+AnOperation()
ConcreteFactory
+FactoryMethod():Product
<<instantiate>>
Factory Method: Participants
8
Product defines the interface for objects the factory method creates.
ConcreteProduct Implements the product interface.
Factory Declares the method FactoryMethod() which returns a Product
object. May call the generating method for creating Product objects.
ConcreteFactory overrides the generating method for creating ConcreteProduct
objects.
Factory Method: Implementation
9
1st way
1.Declare the factory as abstract
and let the subclasses create the object
2nd way
1.Create the factory with a method that takes a
parameter to determine which object should be
crated (parametrized factory method)
Factory Method Structure implementation 1
10
11
12
13
Factory Method Structure: implementation 2
14
Or Better
15
16
17
18
Factory Method: Applicability
The need for implementing the Factory Method is very frequent.
• when a class can't anticipate the type of the objects it is supposed to
create
• when a class wants its subclasses to be the ones to specify the type of
a newly created object
19
Drawbacks and Benefits
•  It introduces a separation between the application and a family of
classes
•  It introduces weak coupling instead of tight coupling hiding
concrete classes from the application.
•  It provides a simple way of extending the family of products with
minor changes in application code.
•  The factory has to be used for a family of objects. If the classes
doesn't extend common base class or interface they can not be used
in a factory design template.
20
Factory Method: hints
• The factory method is one of the most used and one of the more
robust design patterns.
• When you design an application think if you really need a factory to
create objects. Maybe using it will bring unnecessary complexity in
your application.
• If you have many object of the same base type and you manipulate
them mostly as abstract objects, then you need a factory.
• If you're code should have a lot of code like the following, reconsider
it.
21
Another
Exmple
22
Pizza
Cheese Greek Pepperoni
23
Pizza
Cheese Greek Pepperoni
PizzaFactory
ConcreteFactory
PizzaFactory
ConcreteFactory
PizzaFactory
ConcreteFactory
PizzaFactory
ConcreteFactory
What if you want to implement a
PizzaStore App for different
customers: PizzaHot - PizzaDom
– PizzaHat?
24
Abstract Factory
ABSTRACT FACTORY DESIGN PATTERN
Object Creational
Known as Kit
25
Abstract Factory: Intent
• Provide an interface for creating families of related or dependent
objects without specifying their concrete classes.
• A hierarchy that encapsulates many possible "platforms", and the
construction of a suite of "products".
26
Abstract Factory: Motivation
• If an application is to be portable, it needs to
encapsulate platform dependencies.
• EX "platforms": windowing system, operating system,
database, etc.
• In general, this encapsulation is not engineered in
advance
• clients are coded for a specific platform which makes
difficult its portability for other platforms.
27
Abstract Factory: Structure
28
ProductA
ProductB
ProductA2
ProductB2
ProductA1
ProductB1
ConcreteFactory2
+createProductA():ProductA
+createProductB():ProductB
ConcreteFactory1
+createProductA():ProductA
+createProductB():ProductB
<<interface>>
AbstractFactory
+createProductA():ProductA
+createProductB():ProductB
Client
Abstract Factory: Participants
• AbstractFactory: declares an interface for operations that create
abstract product objects
• ConcreteFactory: implements the operations to create concrete
product objects.
• Product: declares an interface for a type of product object
• ConcreteProduct:
• Defines a product object to be created by the corresponding concrete factory
• Implements the Product interface.
• Client: uses only interfaces declared by AbstractFactory and Products
classes.
29
• Sample code
30
Abstract Factory: Applicability
• A system should be independent on how its products
are created, composed and represented.
• A system should be configured with one of multiple
families of products.
• A family of related product objects is designed to be
used together.
• You want to provide a class library of products and
you want to show just the interfaces not their
implementations.
31
Abstract Factory: Example 1
GUI that supports multiple Look & Feel standards
• A GUI framework should support several look and feel
themes
• e.g. Motif and PresentationManager look
• Each style defines different looks and behaviors for each type
of controls: Windows, Scroll Bars, Buttons and Edit Boxes, ...
32
Abstract Factory: Example 2
Pizza Factory Example
• a pizza factory defines method names and returns types to make different
kinds of pizza.
• The abstract factory can be named AbstractPizzaFactory
• It can be implanted by PizzaDomConcretePizzaFactory and
PizzaHotConcretePizzaFactory, etc.
• The abstract factory will define types of toppings for pizza, like pepperoni,
sausage or anchovy
• The concrete factories will implement only a set of the toppings, which are
specific for the area and even if one topping is implemented in both
concrete factories, the resulting pizzas will be different subclasses, each for
the store it was implemented in.
34
Abstract Factory: Example 3
• In the sheet metal stamping equipment used in the manufacture of
Japanese automobiles.
• The stamping equipment is an Abstract
Factory which creates auto body parts.
• The same machinery is used to stamp
right hand doors, left hand doors, right
front fenders, left front fenders, hoods,
etc. for different models of cars.
• Through the use of rollers to change
the stamping dies, the concrete classes
produced by the machinery can be
changed within three minutes.
35
PROTOTYPE DESIGN PATTERN
Object Creational
36
Prototype: Intent
• specify the kind of objects to create using a prototypical instance
• creating new objects by copying this prototype
37
Prototype: Motivation
• Saving costs in creating new objects by cloning rather than
instantiating.
• The Prototype design pattern allows an object to create customized
objects without knowing their class or any details of how to create
them.
38
Prototype: Structure
39
Declares an interface
for cloning itself
Implements an
interface for cloning
itself
Creates a new object by
asking a prototype to
clone itself
Prototype: Sample code
40
Prototype: Applicability
• You need to avoid the creation of a factory hierarchy
• It is more appropriate to copy an existing instance than to create a
new one.
• Use the prototype pattern when the creation of objects directly is
costly (e.g. accessing a database)
41
Read DB and get
tuples
Create Objects
and store them in
a data structure
(e.g. HashMap)
Get a clone of
each object to
manipulate
Prototype: Example
• Application for doing analysis on a set of data from a database.
• Copy the information from the database, encapsulate it into an object
and do the analysis.
• It is possible to need a new analysis on the same set of data
• Reading the database again and creating a new object is costly.
• You can use the Prototype pattern then the object used in the first
analysis will be cloned and used for the other analysis.
• The ConcretePrototype classes will be classes that copy an object
created after extracting data from DB for analysis.
42
Factory Vs Prototype
• Like Factory, Prototype pattern allows an object to create customized
objects without knowing their class or any details of how to create
them.
• The difference between the two patterns:
• Factory Method creates one object of a non existing object type as a fresh
creation (by instantiation).
• Prototype uses the class itself for self duplication action.
43
BUILDER DESIGN PATTERN
Object Creational
44
Builder: Intent
• Separate the construction of a complex object from its representation
so that the same construction process can create different
representations.
Motivation
• An application needs to create the elements of a complex aggregate.
The specification for the aggregate exists on secondary storage and
one of many representations needs to be built in primary storage.
45
Motivation: Example
46
RTF document RTF reader New text format
Plain ASCII text
Text widget
TeXFormat
……
Number of possible
conversions is open-ended!!!
Motivation: Solution
• Configure the RTFReader class with a TextConverter object that
converts RTF to another format.
• TextConverter will be responsible of converting different elements
• Character
• Font
• Paragraph
• Subclasses of textConverter specialize in different conversion and
format.
• e.g: ASCII converters will ignore everything except text
47
Builder: Applicability
Builder Pattern is used when:
• the creation algorithm of a complex object is independent from the
parts that actually compose the object
• the system needs to allow different representations for the objects
that are being built
48
Builder: Structure
49
Director
+construct()
Builder
+buildPart()
ConcreteBuilder
+buildPart()
+getresult()
Product
For each item in structure
builder.buildPart()
Builder: Participants
• The Builder class specifies an abstract interface for creating parts of a
Product object.
• The ConcreteBuilder constructs and puts together parts of the
product by implementing the Builder interface. It defines and keeps
track of the representation it creates and provides an interface for
saving the product.
• The Director class constructs the complex object using the Builder
interface.
• The Product represents the complex object that is being built.
50
Builder: Collaborations
• The client crates the Director object and configures it with the
desired builder
• Director notifies the builder whenever a part should be created.
• Builder handles requests from the director and adds parts to the
product.
• The client retrieves the product from the builder.
51
52
aClient aDirector aBuilder
new Builder()
New Director(aBuilder)
Construct()
BuildPartA()
BuildPartB()
BuildPartC()
getResult()
Builder: Sample code
53
LineObject to be constructed
Rep1First representation
name
part
color
part
length
In cm
Rep2Second representation
name
part
length
In mm
Builder: Example
55
Director
+construct()
Builder
+buildName(name:String):Builder
+buildColor(color:String):Builder
+buildLength(l:float):Builder
Representation1
-name:String
-color:String
-length:float
ConcreteBuilder1
+buildName(…):Builder
+buildColor(…):Builder
+buildLength(…):Builder
+getRep():Representation1
ConcreteBuilder2
+buildName(…):Builder
+buildColor(…):Builder
+buildLength(…):Builder
+getRep():Representation2
-rep -rep
Representation2
-name:String
-length:float
Builder: Common use
• A common use of Builder pattern is when the object to be build has
many attributes.
• It is possible to use many constructors with different parameters but
this choice is difficult to handle when the number of attributes
increases.
56
• Sample code
57
Advantages
• Builder lets you vary a product’s internal representation
• Builder isolates code for construction and representation
• Gives finer control over the construction process
58
Builder: Example 1
• Construct children's meals.
• Children's meals typically consist of
• a main item,
• a side item,
• a drink, and
• a toy
• There can be variation in the content of the children's meal, but the
construction process is the same.
59
Builder: Example 2
Students and admin interface.
• Consider an application that can be used by the students of a University
• The app needs to run in different ways depending on the logged user.
• the admin needs to have some buttons enabled while disabled for the student.
• The Builder provides the interface for building form depending on the login
information.
• The ConcreteBuilders are the specific forms for each type of user.
• The Product is the final form that the application will use in the given case
• The Director is the application that, based on the login information, needs
a specific form.
60
Builder Vs Abstract Factory
• The Builder design pattern is very similar, at some extent, to the
Abstract Factory pattern.
• In the Abstract Factory, the client uses the factory’s methods to create
its own objects in one shot fashion.
• Builder creates object in step by step fashion not in one shot.
• Abstract factory focuses on family of products while the products in
builder are not of the same type.
61
SINGLETON PATTERN
Object Creational
62
Singleton: Intent
• Ensure a class has only one instance, and provide a global point of
access to it.
63
Singleton: Applicability
Use it when
• There must be exactly one instance of a class, and
• it must be accessible to clients from a well known access point
(Provide a global point of access to the object).
64
Singleton: Structure
• Singleton class defines an Instance operation that lets clients access
its unique instance.
• Instance is a class operation.
65
Singleton: easy to understand but difficult to
implement
Implementation with lazy initialization
• The constructor is private to prevent instantiation from outside.
• The unique instance is a class variable.
• A static getter to get the instance and to create it if needed (first
time).
66
Simple but non
thread safe
Implementation
67
Singleton: easy to understand but difficult to
implement
Implementation with lazy initialization + Thread safe
• Declare the getter as synchronized bloc
• Cannot be executed concurrently by two threads
68
Thread safe but time
consuming
Thread safe solution with lazy initialization -
synchronized
69
Thread safe solution with early initialization
70
Singleton: Example 1 - Logger Classes
• The Singleton pattern is used in the design of logger classes.
• Logger classes are usually implemented as singletons
• They provide a global logging access point in all the application
components
71
Singleton: Example 2 - Configuration Classes
• The Singleton pattern is used to design the classes which provides the
configuration settings for an application.
• By implementing configuration classes as Singleton you provide a
global access point.
• You also keep the instance as a cache object.
72
Singleton: Example 3 - Factories implemented
as Singletons
• It is common to combine Abstract Factory or Factory Method and
Singleton design pattern.
• If you design an application with a factory to generate new objects
(Account, Customer, Site, Address objects) with their ids, in
multithreading environment, if the factory is instantiated twice in 2
different threads then it is possible to have 2 overlapping ids for 2
different objects.
73

Contenu connexe

Tendances

Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012
rhrashel
 

Tendances (20)

Design pattern
Design patternDesign pattern
Design pattern
 
CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV CS8592 Object Oriented Analysis & Design - UNIT IV
CS8592 Object Oriented Analysis & Design - UNIT IV
 
[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering[2016/2017] RESEARCH in software engineering
[2016/2017] RESEARCH in software engineering
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Gof design pattern
Gof design patternGof design pattern
Gof design pattern
 
Module 2 design patterns-2
Module 2   design patterns-2Module 2   design patterns-2
Module 2 design patterns-2
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Designpattern
DesignpatternDesignpattern
Designpattern
 
Cse 6007 fall2012
Cse 6007 fall2012Cse 6007 fall2012
Cse 6007 fall2012
 
Software Architecture Course - Part III Taxonomies - Definitions
Software Architecture Course - Part III Taxonomies - DefinitionsSoftware Architecture Course - Part III Taxonomies - Definitions
Software Architecture Course - Part III Taxonomies - Definitions
 
Cs 2352 object oriented analysis and design
Cs 2352 object oriented analysis and designCs 2352 object oriented analysis and design
Cs 2352 object oriented analysis and design
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Jeet ooad unit-2
Jeet ooad unit-2Jeet ooad unit-2
Jeet ooad unit-2
 
Ch06lect1 ud
Ch06lect1 udCh06lect1 ud
Ch06lect1 ud
 
[2016/2017] Introduction to Software Architecture
[2016/2017] Introduction to Software Architecture[2016/2017] Introduction to Software Architecture
[2016/2017] Introduction to Software Architecture
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPTCS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
 
Ch05lect1 ud
Ch05lect1 udCh05lect1 ud
Ch05lect1 ud
 
Oomd unit1
Oomd unit1Oomd unit1
Oomd unit1
 
Ch10lect1 ud
Ch10lect1 udCh10lect1 ud
Ch10lect1 ud
 

Similaire à Creational Patterns

Csc253 chapter 09
Csc253 chapter 09Csc253 chapter 09
Csc253 chapter 09
PCC
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
stanbridge
 
Model builder in arcgis
Model builder in arcgisModel builder in arcgis
Model builder in arcgis
Ashok Peddi
 
Model builder in arcgis
Model builder in arcgisModel builder in arcgis
Model builder in arcgis
Ashok Peddi
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
Deepti C
 

Similaire à Creational Patterns (20)

Creational Design Patterns.pptx
Creational Design Patterns.pptxCreational Design Patterns.pptx
Creational Design Patterns.pptx
 
Code Like a Ninja Session 7 - Creational Design Patterns
Code Like a Ninja Session 7 - Creational Design PatternsCode Like a Ninja Session 7 - Creational Design Patterns
Code Like a Ninja Session 7 - Creational Design Patterns
 
Prototype design patterns
Prototype design patternsPrototype design patterns
Prototype design patterns
 
Weekly Meeting: Basic Design Pattern
Weekly Meeting: Basic Design PatternWeekly Meeting: Basic Design Pattern
Weekly Meeting: Basic Design Pattern
 
Software design with Domain-driven design
Software design with Domain-driven design Software design with Domain-driven design
Software design with Domain-driven design
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Csc253 chapter 09
Csc253 chapter 09Csc253 chapter 09
Csc253 chapter 09
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
 
Model builder in arcgis
Model builder in arcgisModel builder in arcgis
Model builder in arcgis
 
Nodejs Chapter 3 - Design Pattern
Nodejs Chapter 3 - Design PatternNodejs Chapter 3 - Design Pattern
Nodejs Chapter 3 - Design Pattern
 
Effective java
Effective javaEffective java
Effective java
 
Model builder in arcgis
Model builder in arcgisModel builder in arcgis
Model builder in arcgis
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and Dapper
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 

Dernier

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Creational Patterns

  • 1. CPIT-252 DESIGN PATTERNS Teacher: Dr. Asma Cherif Office room: 144S email: acherif@kau.edu.sa IT dept. Course Coordinator: Dr. Asma Cherif 1
  • 2. REFERENCES Many resources have been used to build this course, if you notice any missing reference please contact me at acherif@kau.edu.sa • Roger S. Pressman, "Software Engineering: A Practitioner’s Approach", McGraw-Hill Science/Engineering/Math; 7 edition (2010) • GoF book • Laurent Audibert (developpez.com) • Dr. Birgit Demuth (OCL) • Dr. K.M Anderson • Head First Collection • Software engineering, Ian Sommerville, ch2- quality management • www.newthinktank.com • https://sourcemaking.com • Derek Banas youtube channel 2
  • 5. FACTORY METHOD DESIGN PATTERN Class Creational Known as Virtual Constructor 5
  • 6. Factory Method Pattern • Factory pattern is one of the most used design patterns in Java. • Provides one of the best ways to create objects related with inheritance relationship (of same type) • Allows to create objects without exposing the creation logic to the client and refer to newly created object using a common interface. 6
  • 7. Factory Method: Intent Define an interface for creating an object but let subclasses decide which class to instantiate. 7 Factory Method: general structure Product ConcreteProduct Factory +FactoryMethod():Product +AnOperation() ConcreteFactory +FactoryMethod():Product <<instantiate>>
  • 8. Factory Method: Participants 8 Product defines the interface for objects the factory method creates. ConcreteProduct Implements the product interface. Factory Declares the method FactoryMethod() which returns a Product object. May call the generating method for creating Product objects. ConcreteFactory overrides the generating method for creating ConcreteProduct objects.
  • 9. Factory Method: Implementation 9 1st way 1.Declare the factory as abstract and let the subclasses create the object 2nd way 1.Create the factory with a method that takes a parameter to determine which object should be crated (parametrized factory method)
  • 10. Factory Method Structure implementation 1 10
  • 11. 11
  • 12. 12
  • 13. 13
  • 14. Factory Method Structure: implementation 2 14
  • 16. 16
  • 17. 17
  • 18. 18
  • 19. Factory Method: Applicability The need for implementing the Factory Method is very frequent. • when a class can't anticipate the type of the objects it is supposed to create • when a class wants its subclasses to be the ones to specify the type of a newly created object 19
  • 20. Drawbacks and Benefits •  It introduces a separation between the application and a family of classes •  It introduces weak coupling instead of tight coupling hiding concrete classes from the application. •  It provides a simple way of extending the family of products with minor changes in application code. •  The factory has to be used for a family of objects. If the classes doesn't extend common base class or interface they can not be used in a factory design template. 20
  • 21. Factory Method: hints • The factory method is one of the most used and one of the more robust design patterns. • When you design an application think if you really need a factory to create objects. Maybe using it will bring unnecessary complexity in your application. • If you have many object of the same base type and you manipulate them mostly as abstract objects, then you need a factory. • If you're code should have a lot of code like the following, reconsider it. 21
  • 24. What if you want to implement a PizzaStore App for different customers: PizzaHot - PizzaDom – PizzaHat? 24 Abstract Factory
  • 25. ABSTRACT FACTORY DESIGN PATTERN Object Creational Known as Kit 25
  • 26. Abstract Factory: Intent • Provide an interface for creating families of related or dependent objects without specifying their concrete classes. • A hierarchy that encapsulates many possible "platforms", and the construction of a suite of "products". 26
  • 27. Abstract Factory: Motivation • If an application is to be portable, it needs to encapsulate platform dependencies. • EX "platforms": windowing system, operating system, database, etc. • In general, this encapsulation is not engineered in advance • clients are coded for a specific platform which makes difficult its portability for other platforms. 27
  • 29. Abstract Factory: Participants • AbstractFactory: declares an interface for operations that create abstract product objects • ConcreteFactory: implements the operations to create concrete product objects. • Product: declares an interface for a type of product object • ConcreteProduct: • Defines a product object to be created by the corresponding concrete factory • Implements the Product interface. • Client: uses only interfaces declared by AbstractFactory and Products classes. 29
  • 31. Abstract Factory: Applicability • A system should be independent on how its products are created, composed and represented. • A system should be configured with one of multiple families of products. • A family of related product objects is designed to be used together. • You want to provide a class library of products and you want to show just the interfaces not their implementations. 31
  • 32. Abstract Factory: Example 1 GUI that supports multiple Look & Feel standards • A GUI framework should support several look and feel themes • e.g. Motif and PresentationManager look • Each style defines different looks and behaviors for each type of controls: Windows, Scroll Bars, Buttons and Edit Boxes, ... 32
  • 33.
  • 34. Abstract Factory: Example 2 Pizza Factory Example • a pizza factory defines method names and returns types to make different kinds of pizza. • The abstract factory can be named AbstractPizzaFactory • It can be implanted by PizzaDomConcretePizzaFactory and PizzaHotConcretePizzaFactory, etc. • The abstract factory will define types of toppings for pizza, like pepperoni, sausage or anchovy • The concrete factories will implement only a set of the toppings, which are specific for the area and even if one topping is implemented in both concrete factories, the resulting pizzas will be different subclasses, each for the store it was implemented in. 34
  • 35. Abstract Factory: Example 3 • In the sheet metal stamping equipment used in the manufacture of Japanese automobiles. • The stamping equipment is an Abstract Factory which creates auto body parts. • The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. • Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes. 35
  • 37. Prototype: Intent • specify the kind of objects to create using a prototypical instance • creating new objects by copying this prototype 37
  • 38. Prototype: Motivation • Saving costs in creating new objects by cloning rather than instantiating. • The Prototype design pattern allows an object to create customized objects without knowing their class or any details of how to create them. 38
  • 39. Prototype: Structure 39 Declares an interface for cloning itself Implements an interface for cloning itself Creates a new object by asking a prototype to clone itself
  • 41. Prototype: Applicability • You need to avoid the creation of a factory hierarchy • It is more appropriate to copy an existing instance than to create a new one. • Use the prototype pattern when the creation of objects directly is costly (e.g. accessing a database) 41 Read DB and get tuples Create Objects and store them in a data structure (e.g. HashMap) Get a clone of each object to manipulate
  • 42. Prototype: Example • Application for doing analysis on a set of data from a database. • Copy the information from the database, encapsulate it into an object and do the analysis. • It is possible to need a new analysis on the same set of data • Reading the database again and creating a new object is costly. • You can use the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis. • The ConcretePrototype classes will be classes that copy an object created after extracting data from DB for analysis. 42
  • 43. Factory Vs Prototype • Like Factory, Prototype pattern allows an object to create customized objects without knowing their class or any details of how to create them. • The difference between the two patterns: • Factory Method creates one object of a non existing object type as a fresh creation (by instantiation). • Prototype uses the class itself for self duplication action. 43
  • 45. Builder: Intent • Separate the construction of a complex object from its representation so that the same construction process can create different representations. Motivation • An application needs to create the elements of a complex aggregate. The specification for the aggregate exists on secondary storage and one of many representations needs to be built in primary storage. 45
  • 46. Motivation: Example 46 RTF document RTF reader New text format Plain ASCII text Text widget TeXFormat …… Number of possible conversions is open-ended!!!
  • 47. Motivation: Solution • Configure the RTFReader class with a TextConverter object that converts RTF to another format. • TextConverter will be responsible of converting different elements • Character • Font • Paragraph • Subclasses of textConverter specialize in different conversion and format. • e.g: ASCII converters will ignore everything except text 47
  • 48. Builder: Applicability Builder Pattern is used when: • the creation algorithm of a complex object is independent from the parts that actually compose the object • the system needs to allow different representations for the objects that are being built 48
  • 50. Builder: Participants • The Builder class specifies an abstract interface for creating parts of a Product object. • The ConcreteBuilder constructs and puts together parts of the product by implementing the Builder interface. It defines and keeps track of the representation it creates and provides an interface for saving the product. • The Director class constructs the complex object using the Builder interface. • The Product represents the complex object that is being built. 50
  • 51. Builder: Collaborations • The client crates the Director object and configures it with the desired builder • Director notifies the builder whenever a part should be created. • Builder handles requests from the director and adds parts to the product. • The client retrieves the product from the builder. 51
  • 52. 52 aClient aDirector aBuilder new Builder() New Director(aBuilder) Construct() BuildPartA() BuildPartB() BuildPartC() getResult()
  • 54. LineObject to be constructed Rep1First representation name part color part length In cm Rep2Second representation name part length In mm
  • 56. Builder: Common use • A common use of Builder pattern is when the object to be build has many attributes. • It is possible to use many constructors with different parameters but this choice is difficult to handle when the number of attributes increases. 56
  • 58. Advantages • Builder lets you vary a product’s internal representation • Builder isolates code for construction and representation • Gives finer control over the construction process 58
  • 59. Builder: Example 1 • Construct children's meals. • Children's meals typically consist of • a main item, • a side item, • a drink, and • a toy • There can be variation in the content of the children's meal, but the construction process is the same. 59
  • 60. Builder: Example 2 Students and admin interface. • Consider an application that can be used by the students of a University • The app needs to run in different ways depending on the logged user. • the admin needs to have some buttons enabled while disabled for the student. • The Builder provides the interface for building form depending on the login information. • The ConcreteBuilders are the specific forms for each type of user. • The Product is the final form that the application will use in the given case • The Director is the application that, based on the login information, needs a specific form. 60
  • 61. Builder Vs Abstract Factory • The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. • In the Abstract Factory, the client uses the factory’s methods to create its own objects in one shot fashion. • Builder creates object in step by step fashion not in one shot. • Abstract factory focuses on family of products while the products in builder are not of the same type. 61
  • 63. Singleton: Intent • Ensure a class has only one instance, and provide a global point of access to it. 63
  • 64. Singleton: Applicability Use it when • There must be exactly one instance of a class, and • it must be accessible to clients from a well known access point (Provide a global point of access to the object). 64
  • 65. Singleton: Structure • Singleton class defines an Instance operation that lets clients access its unique instance. • Instance is a class operation. 65
  • 66. Singleton: easy to understand but difficult to implement Implementation with lazy initialization • The constructor is private to prevent instantiation from outside. • The unique instance is a class variable. • A static getter to get the instance and to create it if needed (first time). 66 Simple but non thread safe
  • 68. Singleton: easy to understand but difficult to implement Implementation with lazy initialization + Thread safe • Declare the getter as synchronized bloc • Cannot be executed concurrently by two threads 68 Thread safe but time consuming
  • 69. Thread safe solution with lazy initialization - synchronized 69
  • 70. Thread safe solution with early initialization 70
  • 71. Singleton: Example 1 - Logger Classes • The Singleton pattern is used in the design of logger classes. • Logger classes are usually implemented as singletons • They provide a global logging access point in all the application components 71
  • 72. Singleton: Example 2 - Configuration Classes • The Singleton pattern is used to design the classes which provides the configuration settings for an application. • By implementing configuration classes as Singleton you provide a global access point. • You also keep the instance as a cache object. 72
  • 73. Singleton: Example 3 - Factories implemented as Singletons • It is common to combine Abstract Factory or Factory Method and Singleton design pattern. • If you design an application with a factory to generate new objects (Account, Customer, Site, Address objects) with their ids, in multithreading environment, if the factory is instantiated twice in 2 different threads then it is possible to have 2 overlapping ids for 2 different objects. 73

Notes de l'éditeur

  1. ghmhn
  2. All concrete products are subclasses of the Product class, so all of them have the same basic implementation, at some extent. The Creator class specifies all standard and generic behavior of the products and when a new product is needed, it sends the creation details that are supplied by the client to the ConcreteCreator. Having this diagram in mind, it is easy for us now to produce the code related to it.
  3.  It provides customization hooks. When the objects are created directly inside the class it's hard to replace them by objects which extend their functionality. If a factory is used instead to create a family of objects the customized objects can easily replace the original objects, configuring the factory to create them.
  4. If an application is to be portable, it needs to encapsulate platform dependencies. These "platforms" might include: windowing system, operating system, database, etc. Too often, this encapsulation is not engineered in advance, and clients are coded for a specific platform which makes difficult its portability for other platforms.
  5. PM presentation managerIn order to avoid the hard coding for each type of control, define an abstract class WidgetFactory. The client will instantiate, depending on a configuration parameter in the application one of the concrete factories: MotifWidgetFactory or PMWidgetFactory. Each request for a new object will be delegated to the instantiated concrete factory which will return the controls with the specific flavor
  6. The stamping equipment is an Abstract Factory which creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes.
  7. In both these patterns, the client can create any of the derived class objects without knowing anything about their own structure.
  8. Example Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants.
  9. Logging is the process of writing log messages during the execution of a program to a central place. This logging allows you to report and persist error and warning messages as well as info messages (e.g., runtime statistics) so that the messages can later be retrieved and analyzed. The object which performs the logging in applications is typically just called Logger.
  10. When the class is instantiated (or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids reloading the values each time the configuration parameters are used.