0% found this document useful (0 votes)
60 views72 pages

Unit-Ii: Creational Patterns

The document discusses creational patterns and the abstract factory pattern specifically. It defines abstract factory as providing an interface for creating families of related or dependent objects without specifying their concrete classes. This allows a system to be independent of how products are created, composed, and represented. The abstract factory pattern centralizes the decision of which concrete factory to instantiate.

Uploaded by

Denamo Markos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views72 pages

Unit-Ii: Creational Patterns

The document discusses creational patterns and the abstract factory pattern specifically. It defines abstract factory as providing an interface for creating families of related or dependent objects without specifying their concrete classes. This allows a system to be independent of how products are created, composed, and represented. The abstract factory pattern centralizes the decision of which concrete factory to instantiate.

Uploaded by

Denamo Markos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

UNIT-II

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

• Abstracts instantiation process


- Makes system independent of how its objects are
created, composed, represented
• Important if systems evolve to depend more on object
composition than on class inheritance
– Emphasis shifts from hardcoding fixed sets of
behaviors towards a smaller set of composable
fundamental behaviors
• CDP are composed of Two Distinct Ideas.
1. Encapsulates knowledge about which concrete
classes the system uses
2. Hides how instances of these classes are created
and put together UNIT-II 3
L1
Creational Patterns
• For example in java the simplest way to
create an instance of an object is by using
the new operator.
garden = new garden(); // instance of
garden class.

UNIT-II 4
L1
What are creational patterns?

• Design patterns that deal with object


creation mechanisms, trying to create
objects in a manner suitable to the
situation
• Make a system independent of the way in
which objects are created, composed and
represented
• Recurring themes:
– Encapsulate knowledge about which concrete
classes the system uses (so we can change
them easily later)
– Hide how instances of these classes are created
and put together (soUNIT-II
we can change it easily 5
later)
Creational patterns cont..
• Definition: The creational patterns aim to separate a system from how its objects
are created, composed, and represented. They increase the system's flexibility in
terms of the what, who, how, and when of object creation.
• Usage: Consider applying creational patterns when:
A system should be independent of how its objects and products are created.
 A set of related objects is designed to be used together.
 Hiding the implementations of a class library of product, revealing only
their interfaces.
 Constructing different representation of independent complex objects.
 A class want its subclass to implement the object it creates.
 The class instantiations are specified at run-time.
 There must be a single instance and client can access this instance at all
times.
 Instance should be extensible without being modified.
 Structure: Simple class Diagram that most CP have an common. Note that different
CP require additional and different participants.
 Participants: Creator- Declares object Interface, return objects
 Concrete creator- implement object Interface.
UNIT-II 6
L1

Benefits of creational patterns


• Creational patterns let you program to
an interface defined by an abstract
class
• That lets you configure a system with
“product” objects that vary widely in
structure and functionality
• Example: GUI systems
– InterViews GUI class library
– Multiple look-and-feels
– Abstract Factories for different screen
components UNIT-II 7
L1

Benefits of creational patterns


• Generic instantiation – Objects are instantiated
without having to identify a specific class type
in client code (Abstract Factory, Factory)
• Simplicity – Make instantiation easier: callers
do not have to write long complex code to
instantiate and set up an object (Builder,
Prototype pattern)
• Creation constraints – Creational patterns can
put bounds on who can create objects, how
they are created, and when they are created

UNIT-II 8
L2

Abstract Factory Pattern

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

• Also Known As: Kit.

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

Use the Abstract Factory pattern when


– A system should be independent of how its products
are created, composed, and represented
– A system should be configured with one of multiple
families of produces
– A family of related product objects is designed to be
used together, and you need to enforce this
constraint
– You want to provide a class library of products, and
you want to reveal just their interfaces, not their
implementations

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

• Usually only one ConcreteFactory instance is


used for an activation, matched to a specific
application context. It builds a specific product
family for client use -- the client doesn’t care
which family is used -- it simply needs the
services appropriate for the current context.

• The client may use the AbstractFactory


interface to initiate creation, or some other
agent may use the AbstractFactory on the
client’s behalf.
UNIT-II 20
L2

Presentation Remark

• Here, we often use a sequence diagram


(event-trace) to show the dynamic
interactions between participants.

• For the Abstract Factory Pattern, the


dynamic interaction is simple, and a
sequence diagram would not add much
new information.

UNIT-II 21
L2
Consequences

• The Abstract Factory Pattern has the following


benefits:
It isolates concrete classes from the client.
• You use the Abstract Factory to control the classes of objects the
client creates.
• Product names are isolated in the implementation of the
ConcreteFactory, clients use the instances through their abstract
interfaces.
• Exchanging product families is easy.
• None of the client code breaks because the abstract interfaces
don’t change.
• Because the abstract factory creates a complete family of products,
the whole product family changes when the concrete factory is
changed.
It promotes consistency among products.
• It is the concrete factory’s job to make sure that the right products
UNIT-II 22
are used together.
L2

Consequences

• More benefits of the Abstract Factory


Pattern
– It supports the imposition of constraints on
product families, e.g., always use A1 and
B1 together, otherwise use A2 and B2
together.

UNIT-II 23
L2
Consequences

• The Abstract Factory pattern has the


following liability:
Adding new kinds of products to existing factory is
difficult.
• Adding a new product requires extending the abstract
interface which implies that all of its derived concrete
classes also must change.
• Essentially everything must change to support and
use the new product family
– abstract factory interface is extended
– derived concrete factories must implement the extensions
– a new abstract product class is added
– a new product implementation is added
– client has to be extended
UNIT-IIto use the new product 24
Implementation L2

• Concrete factories are often implemented as


singletons.
Creating the products
– Concrete factory usually use the factory method.
• simple
• new concrete factory is required for each product
family
• alternately concrete factory can be
implemented using prototype.
• only one is needed for all families of products
• product classes now have special requirements - they
participate in the creation
UNIT-II 25
L2

Implementation

• Defining extensible factories by using


create function with an argument
– only one virtual create function is needed
for the AbstractFactory interface
– all products created by a factory must have
the same base class or be able to be
safely coerced to a given type
– it is difficult to implement subclass specific
operations

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).

• COM – Microsoft’s Component Object Model technology


– Each COM component provides a concrete factory bound to the
IClassFactory interface and provides clients specific instances bound to
the server’s product interface.

UNIT-II 27
L2

Related Patterns

• Factory Method -- a “virtual” constructor

• Prototype -- asks products to clone


themselves

• Singleton -- allows creation of only a


single instance

UNIT-II 28
L2

Code Examples

• Skeleton Example
– Abstract Factory Structure
– Skeleton Code

• Neural Net Example


– Neural Net Physical Structure
– Neural Net Logical Structure
– Simulated Neural Net Example

UNIT-II 29
Builder Pattern
• Make and return one Object various ways

• The Builder Pattern assembles a number of


objects to make a new object, based on the data
with which it is presented. Frequently, the choice
of which way the objects are assembled is
achieved using a Factory.

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()

while(t=get the next token){


switch t.Type{ ASCIIConverter TextConverter TextWidgestConverter
CHAR: ConvertCharacter(char) ConvertCharacter(char)
ConvertCharacter(char)
builder->ConvertCharacter(t.Char)
FONT: GetASCIIText() ConvertFontChange(Font) ConvertFontChange(Font)
builder->ConventFontCharnge(t.Font) ConvertParagraph() ConvertParagraph()
PARA:
GetTeXText() GetTextWidget()
Builder->ConventParagraph()
}
}

ASCIIText TeXText TextWidget

UNIT-II 33
L3

Applicability

• Use the Builder pattern when


– The algorithm for creating a complex object
should be independent of the parts that make
up the object and how they are assembled
– The construction process must allow different
representations for the object that is
constructed

UNIT-II 34
L3

BUILDER
Structure
builders
Director Builder

BuildPart ()
Construct ()

for all objects in structure {


builder->BuildPart ()
}
ConcreteBuilder Product

BuildPart ()
GetResult ()

UNIT-II 35
Builder - Collaborations L3

• Client creates Director object and configures it with


the desired Builder object

• Director notifies Builder whenever a part of the


product should be built

• Builder handles requests from the Director and adds


parts to the product

• Client retrieves the product from the Builder

UNIT-II 36
L3

Participants & Collaborations

Constructs an
Object
Parameter of of Concrete type
Abstract type (ConcreteBuilder
(Builder Class)
Interface)

Controls all the


Process
to Construct an
Instance Product

Director
UNIT-II 37
L3

BUILDER
Collaborations
aClient aDirector aConcreteBuilder

new ConcreteBuilder

new Director (aConcreteBuilder)

BuildPart A ()

BuilPart B ()

BuildPart C ()

GetResult ()

UNIT-II 38
L3

Why do we use Builder?


• Common manner public class Room {
private int area;
to Create an private int windows;
public String purpose;
Instance
– Constructor! Room() {
}
– Each Parts
determined by Room(int newArea, int
newWindows, String newPurpose){
Parameter of the area = newArea;
Constructor windows = newWindows;
purpose = newPurpose;
}
} There are Only 2 different
ways
to Create an Instance part-
UNIT-IIby-part. 39
L3

Why do we use Builder?


• In the previous example,
– We can either determine all the arguments
or determine nothing and just construct.
We can’t determine arguments partially.
– We can’t control whole process to
Create an instance.
– Restriction of ways to Create an Object
☞ Bad Abstraction & Flexibility

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

– Defines the interface of objects the factory method creates


• ConcreteProduct
– Implements the product interface
• Creator
– Declares the factory method which returns object of type product May
contain a default implementation of the factory method Creator relies
on its subclasses to define the factory method so that it returns an
instance of the appropriate Concrete Product. ConcreteCreator
Overrides factory method to return instance of ConcreteProduct

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()

UNIT-II return new ConcreteProduct();


50
L4

Factory Method (2)


• Example: creating manipulators on connectors

Interactor
0..1
Figure Manipulator
createManipulator() attach(Figure)

RectFigure ConnectorBoundsManipulatorArcManipulator
createManipulator() createManipulator() attach(Figure) attach(Figure)

manip = new ArcManipulator();

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

Rotate Tool Graphic Tool Draw(Position)

Manipulate() Manipulate() Clone()

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

• Use the Prototype pattern when a system


should be independent of how its products
are created, composed, and represented;
– when the classes to instantiate are specified at
run-time, for example, by dynamic loading; or
– to avoid building a class hierarchy of factories
that parallels the class hierarchy of products; or

UNIT-II 56
L5
Applicability

– when instances of a class can have one of


only a few different combinations of state. It
may be more convenient to install a
corresponding number of prototypes and
clone them rather than instantiating the class
manually, each time with the appropriate
state.

UNIT-II 57
L5

PROTOTYPE
Structure
client prototype
Prototype

Operation() Clone()

p = prototype ->Clone()

ConcretePrototype1 ConcretePrototype2

Clone() Clone()

return copy of self


return copy of self

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

• Use the Singleton pattern when


– there must be exactly one instance of a
class, and it must be accessible to clients
from a well-known access point.
– when the sole instance should be extensible
by subclassing, and clients should be able to
use an extended instance without modifying
their code.
UNIT-II 62
L6

SINGLETON
Structure

Singleton

static Instance() return uniquelnstance

SingletonOperation()
GetSingletonData()

Static uniquelnstance
singletonData

UNIT-II 63
L6

Participants and Collaborations


• Singleton:
• Defines an instance operation that lets clients
access its unique interface
• Instance is a class operation (static in Java)
• May be responsible for creating its own unique
instance
• Collaborations:
• Clients access a Singleton instance solely
through Singleton’s Instance operation.

UNIT-II 64
L6

Singleton
• Ensures a class has only one instance

• Provides a single point of reference

UNIT-II 65
L6

Singleton – Use When


• There must be exactly one instance of a
class.

• May provide synchronous access to


avoid deadlocks.

• Very common in GUI toolkits, to specify


the connection to the OS/Windowing
system
UNIT-II 66
L6

Singleton - Benefits
• Controls access to a scarce (limited) or
unique resource

• Helps avoid a central application class with


various global object references

• Subclasses can have different


implementations as required. Static or global
references don’t allow this Multiple or single
instances can be allowed
UNIT-II 67
L6

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

Singleton Code [1]


class Singleton { // Only one instance can ever be created.

public:
static Singleton* Instance();

protected:
// Creation hidden inside Instance().
Singleton();

private:
Static Singleton* _instance

} // Cannot access directly.


UNIT-II 70
L6

Singleton Code [2]


Singleton* Singleton::_instance=0;

Singleton* Singleton:: Instance(){

if (_instance ==0) {
_instance=new Singleton;
}
Return _instance;

// Clients access the singleton


// exclusively via the Instance member
// function.

UNIT-II 71
L6

Implementation Points
• Generally, a single instance is held by
the object, and controlled by a single
interface.

• Sub classing the Singleton may provide


both default and overridden
functionality.

UNIT-II 72

You might also like