Unit-Ii: Creational Patterns
Unit-Ii: Creational Patterns
Creational Patterns
UNIT-II 1
Creational Patterns
• Creational Design patterns (CDP) are design
patterns that deals with object creation
mechanism, try to create objects in a manner
suitable to the situation.
• Creational DP solve the design problems by
some how controlling the object creation.
• All the CDP deals with the best way to create
instances of objects. This is important because
your program should not depend on how objects
are created and arranged.
UNIT-II 2
Creational Patterns Cont.. L1
UNIT-II 4
L1
What are creational patterns?
UNIT-II 8
L2
UNIT-II 9
L2
Abstract Factory
Provide an interface for creating families of related or
dependent objects without specifying their concrete classes
Abstract factory pattern: centralize decision of what factory to
instantiate
The AFP is a software design pattern that provides a way to
encapsulate a group of individual factories that have a
common theme. In normal usage, the client software creates
a concrete implementation of the abstract factory and then
uses the generic interfaces to create the concrete objects
that are part of the theme.
UNIT-II 10
AFP Cont..
An example of this would be an abstract factory
class DocumentCreator that provides interfaces to
create a number of products (e.g. createLetter() &
createResume()). The system would have any
number of derived concrete versions of the
DocumentCreator class like FancyDocumentCreator or
ModernDocumentCreator, each with a different
implementation of createLetter() and createResume()
that would create a corresponding object like
FancyLetter or ModernResume.
UNIT-II 11
L2
ABSTRACT FACTORY
(Object Creational)
• Intent:
– Provide an interface for creating families of
related or dependent objects without
specifying their concrete classes
UNIT-II 12
L2
Motivation
• Motivation:
•User interface toolkit supports multiple
look-and-feel standards
(Motif, Presentation Manager)
•Different appearances and behaviors for
UI widgets
•Apps should not hard-code its widgets
UNIT-II 13
L2
ABSTRACT FACTORY
Motivation
Widget Factory Client
CreateScrollBar()
CreateWindow()
Windows
PMWindow MotifWindow
MotifWidgetFactory PMWidgetFactory
CreateScrollBar() CreateScrollBar()
ScrollBar
CreateWindow() CreateWindow()
PMScrollBar MotifScrollBar
UNIT-II 14
L2
Solution:
• Solution:
•Abstract Widget Factory class
•Interfaces for creating each basic kind
of widget
•Abstract class for each kind of widgets,
•Concrete classes implement specific
look-and-feel.
UNIT-II 15
Abstract Factory Structure L2
client
AbstractProductA
AbstractFactory
Operations:
CreateProdA( )
CreateProcB( )
ConcreteProductA1 ConcreteProductA2
ConcreteFactory1 ConcreteFactory2
Operations: Operations:
CreateProdA( ) CreateProdA( )
CreateProcB( ) CreateProcB( )
AbstractProductB
ConcreteProductB1 ConcreteProductB2
UNIT-II 16
Applicability L2
UNIT-II 17
L2
ABSTRACT FACTORY
Participants
• AbtractFactory
– Declares interface for operations that create
abstract product objects
• ConcreteFactory
– Implements operations to create concrete
product objects
• AbstractProduct
– Declares an interface for a type of product
object
UNIT-II 18
L2
• ABSTRACT FACTORY
Participants(cont..)
• Concrete Product:
•Defines a product object to be created by
concrete factory
•Implements the abstract product interface
• Client:
•Uses only interfaces declared by Abstract
Factory and AbstractProduct classes
UNIT-II 19
Collaborators L2
Presentation Remark
UNIT-II 21
L2
Consequences
Consequences
UNIT-II 23
L2
Consequences
Implementation
UNIT-II 26
L2
Know Uses
• Interviews
– used to generate “look and feel” for specific user interface objects
– uses the Kit suffix to denote AbstractFactory classes, e.g., WidgetKit
and DialogKit.
• also includes a layoutKit that generates different composite objects
depending on the needs of the current context
ET++
– another windowing library that uses the AbstractFactory to achieve
portability across different window systems (X Windows and SunView).
UNIT-II 27
L2
Related Patterns
UNIT-II 28
L2
Code Examples
• Skeleton Example
– Abstract Factory Structure
– Skeleton Code
UNIT-II 29
Builder Pattern
• Make and return one Object various ways
UNIT-II 30
BUILDER L3
(Object Creational)
• Intent:
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations
• Motivation:
– RTF reader should be able to convert RTF to
many text format
– Adding new conversions without modifying the
reader should be easy
UNIT-II 31
L3
• Solution:
•Configure RTFReader class with a Text
Converter object
•Subclasses of Text Converter specialize
in different conversions and formats
•TextWidgetConverter will produce a
complex UI object and lets the user see
and edit the text
UNIT-II 32
L3
BUILDER
Motivation
RTFReader builders TextConverter
ParseRTF() ConvertCharacter(char)
ConvertFontChange(Font)
ConvertParagraph()
UNIT-II 33
L3
Applicability
UNIT-II 34
L3
BUILDER
Structure
builders
Director Builder
BuildPart ()
Construct ()
BuildPart ()
GetResult ()
UNIT-II 35
Builder - Collaborations L3
UNIT-II 36
L3
Constructs an
Object
Parameter of of Concrete type
Abstract type (ConcreteBuilder
(Builder Class)
Interface)
Director
UNIT-II 37
L3
BUILDER
Collaborations
aClient aDirector aConcreteBuilder
new ConcreteBuilder
BuildPart A ()
BuilPart B ()
BuildPart C ()
GetResult ()
UNIT-II 38
L3
UNIT-II 40
L3
Discussion
• Uses Of Builder
– Parsing Program(RTF converter)
– GUI
– A reader for the RTF (Rich Text Format) document
exchange format should be able to convert RTF to
many text formats. Ex. an ASCIIConverter, A
TextWidgetConverter.
UNIT-II 41
Factory Method
• Methods to make and return components of
one object various ways.
• The Factory Method provides a simple
decision making class that returns one of
several possible subclasses of an abstract base
class depending on the data that are provided.
• One type of pattern that we see again and again in OO
programs is the Factory pattern or class. A Factory
pattern is one that returns an instance of one of several
possible classes depending on the data provided to it.
• Usually all of the classes it returns have a common
parent class and common methods, but each of them
performs a task differently and is optimized for different
kinds of data. UNIT-II 42
F M P Cont..
Ex. Simple Base class that takes a string and split it into
two Names (first and Last name)
class Namer {
//a simple class to take a string apart into two names
protected String last; //store last name here
protected String first; //store first name here
public String getFirst() {
return first; //return first name
}
public String getLast() {
return last; //return last name
}}
UNIT-II 43
FACTORY METHOD L4
• Intent:
(Class Creational)
– Define an interface for creating an object, but let subclasses
decide which class to instantiate.
– Factory Method lets a class defer instantiation to subclasses.
• Motivation:
– Framework use abstract classes to define and maintain
relationships between objects
– Framework has to create objects as well - must instantiate
classes but only knows about abstract classes - which it cannot
instantiate
UNIT-II 44
L4
Motivation:
• Motivation: Factory method encapsulates
knowledge of which subclass to create -
moves this knowledge out of the
framework
• Also Known As: Virtual Constructor
UNIT-II 45
L4
FACTORY METHOD
Motivation
docs
Document Application
Open()
CreateDocument() Document* doc=CreateDocument();
Close()
NewDocument() docs.Add(doc);
Save() doc->Open();
OpenDocument()
Revert()
MyApplication
MyDocument
return new MyDocument
CreateDocument()
UNIT-II 46
L4
Applicability
• Use the Factory Method pattern when
– a class can´t anticipate the class of objects it
must create.
– a class wants its subclasses to specify the
objects it creates.
– classes delegate responsibility to one of
several helper subclasses, and you want to
localize the knowledge of which helper
subclass is the delegate.
UNIT-II 47
L4
FACTORY METHOD
Structure
Creator
Product
FactoryMethod() ...
product = FactoryMethod()
AnOperation() ...
ConcreteCreator
ConcreteProduct
return new ConcreteProduct
FactoryMethod()
UNIT-II 48
• Product
Participants L4
UNIT-II 49
L4
Factory Method
• Defer object instantiation to subclasses
• Eliminates binding of application-specific subclasses
• Connects parallel class hierarchies
• A related pattern is AbstractFactory
Product Creator
operation() Product createProduct()
ConcreteProduct ConcreteCreator
operation() Product createProduct()
Interactor
0..1
Figure Manipulator
createManipulator() attach(Figure)
RectFigure ConnectorBoundsManipulatorArcManipulator
createManipulator() createManipulator() attach(Figure) attach(Figure)
UNIT-II
manip = new BoundsManipulator(); 51
Prototype Pattern
• Make new objects by cloning the objects which is set
as prototype.
• The Prototype Pattern starts with an initialized and
instantiated class and copies or clones it to make new
instances rather than creating new instances.
• The Prototype pattern is used when creating an instance of
a class is very time-consuming or complex in some way.
Then, rather than creating more instances, you make
copies of the original instance, modifying them as
appropriate.
• The Prototype Pattern copies or clones an existing class
rather than creating a new instance when creating new
instances is more expensive.
UNIT-II 52
L5
PROTOTYPE
(Object Creational)
• Intent:
– Specify the kinds of objects to create using a
prototypical instance, and create new objects
by copying this prototype.
• Motivation:
– Framework implements Graphic class for
graphical components and GraphicTool class
for tools manipulating/creating those
components
UNIT-II 53
L5
Motivation
– Actual graphical components are application-
specific
– How to parameterize instances of Graphic
Tool class with type of objects to create?
– Solution: create new objects in Graphic Tool
by cloning a prototype object instance
UNIT-II 54
L5
PROTOTYPE
Motivation
Tool Graphic
Manipulate() Draw(Position)
Clone()
prototype
Staff MusicalNote
WholeNote HalfNote
p = prototype ->Clone()
Draw(Position) Draw(Position)
while(user drags mouse){
Clone() Clone()
p ->Draw(new position)
}
Insert p into drawing Return copy of self Return copy of self
UNIT-II 55
L5
Applicability
UNIT-II 56
L5
Applicability
UNIT-II 57
L5
PROTOTYPE
Structure
client prototype
Prototype
Operation() Clone()
p = prototype ->Clone()
ConcretePrototype1 ConcretePrototype2
Clone() Clone()
UNIT-II 58
L5
Participants:
• Prototype (Graphic)
– Declares an interface for cloning itself
• ConcretePrototype (Staff, WholeNote, HalfNote)
– Implements an interface for cloning itself
• Client (GraphicTool)
– Creates a new object by asking a prototype to clone
itself
Collaborations:
• A client asks a prototype to clone Itself.
UNIT-II 59
SINGLETON
• The Singleton Pattern is a class of which
there can be no more than one instance. It
provides a single global point of access to that
instance.
• The singleton pattern is grouped with other CP,
although it is to some extent a non CP. In
programming where you need to make sure that
there can be one and only one instance of a
class.
• Ex. Your system can have only one window
manager or print spooler or a single point of
access to a database engine
UNIT-II 60
L6
SINGELTON
• Intent:
– Ensure a class only has one instance, and
provide a global point of access to it.
• Motivation:
– Some classes should have exactly one
instance (one print spooler, one file system,
one window manager)
– A global variable makes an object accessible
but doesn’t prohibit instantiation of multiple
objects
– Class should be responsible for keeping track
of its sole interface
UNIT-II 61
L6
Applicability
SINGLETON
Structure
Singleton
SingletonOperation()
GetSingletonData()
Static uniquelnstance
singletonData
UNIT-II 63
L6
UNIT-II 64
L6
Singleton
• Ensures a class has only one instance
UNIT-II 65
L6
Singleton - Benefits
• Controls access to a scarce (limited) or
unique resource
Singleton – Example 1
• An Application class, where instantiating it
makes a connection to the base operating
system and sets up the rest of the toolkit’s
framework for the user interface.
• In the Qt toolkit:
QApplication* app = new QApplication(argc, argv)
UNIT-II 68
L6
Singleton – Example 2
• A status bar is required for the application, and
various application pieces need to be able to
update the text to display information to the
user. However, there is only one status bar, and
the interface to it should be limited. It could be
implemented as a Singleton object, allowing
only one instance and a focal point for updates.
This would allow updates to be queued, and
prevent messages from being overwritten too
quickly for the user to read them.
UNIT-II 69
L6
public:
static Singleton* Instance();
protected:
// Creation hidden inside Instance().
Singleton();
private:
Static Singleton* _instance
if (_instance ==0) {
_instance=new Singleton;
}
Return _instance;
UNIT-II 71
L6
Implementation Points
• Generally, a single instance is held by
the object, and controlled by a single
interface.
UNIT-II 72