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

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 havebeen 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
  • 3.
  • 4.
  • 5.
    FACTORY METHOD DESIGN PATTERN ClassCreational 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 Definean 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 Productdefines 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 1stway 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 Structureimplementation 1 10
  • 11.
  • 12.
  • 13.
  • 14.
    Factory Method Structure:implementation 2 14
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
    Factory Method: Applicability Theneed 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
  • 22.
  • 23.
  • 24.
    What if youwant to implement a PizzaStore App for different customers: PizzaHot - PizzaDom – PizzaHat? 24 Abstract Factory
  • 25.
    ABSTRACT FACTORY DESIGNPATTERN 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
  • 28.
  • 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
  • 30.
  • 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: Example1 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
  • 34.
    Abstract Factory: Example2 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: Example3 • 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
  • 36.
  • 37.
    Prototype: Intent • specifythe kind of objects to create using a prototypical instance • creating new objects by copying this prototype 37
  • 38.
    Prototype: Motivation • Savingcosts 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 aninterface for cloning itself Implements an interface for cloning itself Creates a new object by asking a prototype to clone itself
  • 40.
  • 41.
    Prototype: Applicability • Youneed 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 • Applicationfor 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
  • 44.
  • 45.
    Builder: Intent • Separatethe 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 documentRTF reader New text format Plain ASCII text Text widget TeXFormat …… Number of possible conversions is open-ended!!!
  • 47.
    Motivation: Solution • Configurethe 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 Patternis 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
  • 49.
  • 50.
    Builder: Participants • TheBuilder 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 • Theclient 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 newBuilder() New Director(aBuilder) Construct() BuildPartA() BuildPartB() BuildPartC() getResult()
  • 53.
  • 54.
    LineObject to beconstructed Rep1First representation name part color part length In cm Rep2Second representation name part length In mm
  • 55.
  • 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
  • 57.
  • 58.
    Advantages • Builder letsyou 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 Studentsand 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 AbstractFactory • 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
  • 62.
  • 63.
    Singleton: Intent • Ensurea class has only one instance, and provide a global point of access to it. 63
  • 64.
    Singleton: Applicability Use itwhen • 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 • Singletonclass defines an Instance operation that lets clients access its unique instance. • Instance is a class operation. 65
  • 66.
    Singleton: easy tounderstand 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
  • 67.
  • 68.
    Singleton: easy tounderstand 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 solutionwith lazy initialization - synchronized 69
  • 70.
    Thread safe solutionwith 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

Editor's Notes

  • #3 ghmhn
  • #9 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.
  • #21  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.
  • #28 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.
  • #34 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
  • #36  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.
  • #44 In both these patterns, the client can create any of the derived class objects without knowing anything about their own structure.
  • #60 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.
  • #72 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.
  • #73 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.