Creational Patterns Part 1
Creational Patterns Part 1
2
➢ Singleton
o Ensure a class only has one instance, and provide a
global point of access to it.
➢ Abstract Factory
o Provide an interface for creating families of related
or dependent objects without specifying their
concrete classes.
➢Factory Method
o Define an interface for creating an object, but let
subclasses decide which class to instantiate
3
➢Builder
o Separates object construction from its
representation
➢ Prototype
o Allows an object to create customized objects
without knowing their class or any details of how to
create them.
➢ Object Pool
o It is a container which contains some amount of
objects. So, when an object is taken from the pool,
it is not available in the pool until it is put back.
4
5
Name: Singleton
Problem:
How can we guarantee that one and only one
instance of a class can be created?
6
Forces:
Can make an object globally accessible as a global
variable, but this violates encapsulation.
Could use class (static) operations and attributes, but
polymorphic redefinition is not always possible.
Solution:
➢ Create a class with a class operation getInstance().
➢ When class is first accessed, this creates relevant object
instance and returns object identity to client.
➢ On subsequent calls of getInstance(), no new instance is
created, but identity of existing object is returned.
7
Class is responsible for tracking its sole
instance
◦ Make constructor private
◦ Provide static method/field to allow access to the
only instance of the class
Benefit:
◦ Reuse implies better performance
◦ Class encapsulates code to ensure reuse of the
object; no need to burden client
8
Singleton Object identifier for singleton
instance, class scope or static
-uniqueInstance
-singletonData Returns object identifier for
+getInstance( ) unique instance, class-scope
+getSingletonData( ) or static
+singletonOperation( ) Private constructor only accessible
-Singleton( ) via getInstance()
getInstance( ) {
if ( uniqueInstance == null )
{ uniqueInstance = new Singleton( ) }
return uniqueInstance
}
9
Some classes have conceptually one instance
◦ Many printers, but only one print spooler
◦ One file system
◦ One window manager
Naïve: create many objects that represent the
same conceptual instance
Better: only create one object and reuse it
◦ Encapsulate the code that manages the reuse
10
In Java, just define a final static field
public class Singleton {
private Singleton() {…}
final private static Singleton instance
= new Singleton();
public Singleton getInstance() { return instance; }
}
Java semantics guarantee object is created
immediately before first use
11
Example: Code
Class Singleton {
private static Singleton uniqueInstance = null;
private Singleton( ) { .. } // private constructor
public static Singleton getInstance( ) {
if (uniqueInstance == null)
uniqueInstance = new Singleton();
// call constructor
return uniqueInstance;
}
}
12
The office of the
President of the United
States is a Singleton.
The United States
Constitution specifies
the means by which a
president is elected,
limits the term of office,
and defines the order of
succession.
As a result, there can be
at most one active
president at any given
time.
13
To specify a class has only one instance, we
make it inherit from Singleton.
+ controlled access to single object instance
through Singleton encapsulation
+ Can tailor for any finite number of instances
+ namespace not extended by global
variables
- access requires additional message passing
- Pattern limits flexibility, significant redesign
if singleton class later gets many instances
14
15
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".
▪ The new operator considered harmful.
16
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 lots of #ifdef case
statements with options for all currently
supported platforms begin to procreate
Singleton is a special case of Factory where
only one object can be created.
17
Name
◦ Abstract Factory
◦ InterViews Kits
◦ ET++ WindowSystem
◦ AWT Toolkit
◦ The ACE ORB (TAO)
Applicability
◦ different families of components (products)
◦ must be used in mutually exclusive and consistent way
◦ hide existence of multiple families from clients
18
The "factory" object has the responsibility for
providing creation services for the entire platform
family.
Clients never create platform objects directly, they
ask the factory to do that for them.
This mechanism makes exchanging product families
easy because the specific class of the factory object
appears only once in the application - where it is
instantiated.
The application can wholesale replace the entire
family of products simply by instantiating a different
concrete instance of the abstract factory.
19
20
Normally, a single instance of a
ConcreteFactory class is created at runtime.
This creates product objects having a
particular implementation.
To create different product objects, clients
should use a different concrete factory.
AbstractFactory defers creation of product
objects to its ConcreteFactory subclasses.
21
22
Decide if "platform independence" and creation
services are the current source of pain.
Map out a matrix of "platforms" versus
"products".
Define a factory interface that consists of a
factory method per product.
Define a factory derived class for each platform
that encapsulates all references to the new
operator.
The client should retire all references to new, and
use the factory methods to create the product
objects.
23
This pattern is found 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.
24
25
◦ isolate creation and handling of instances from
clients
◦ changing look-and-feel standard at run-time is
easy
reassign a global variable;
recompute and redisplay the interface
◦ makes exchanging product families easy
◦ enforces consistency among products in each
family
26
Abstract Factory can use Singleton in their
implementation.
Abstract Factory has the factory object
producing objects of several classes
Abstract Factory classes are often
implemented with Factory Methods
27
28
Intent
➢ Define an interface for creating an object,
but let subclasses decide which class to
instantiate. Factory Method lets a class defer
instantiation to subclasses.
➢ Defining a "virtual" constructor.
➢ The new operator considered harmful.
29
Problem
A framework needs to standardize the
architectural model for a range of
applications, but allow for individual
applications to define their own domain
objects and provide for their instantiation.
When to use Factory method?
➢ A class can't anticipate the class of objects it
must create.
➢ A class wants its subclasses to specify the
objects it creates.
30
31
An increasingly popular definition of factory
method is: a static method of a class that
returns an object of that class' type.
But unlike a constructor, the actual object it
returns might be an instance of a subclass.
Unlike a constructor, an existing object might
be reused, instead of a new object created.
32
Unlike a constructor, factory methods can have different and
more descriptive names (e.g. Color.make_RGB_color(float red,
float green, float blue)
and
Color.make_HSB_color(float hue, float saturation, float
brightness)
33
34
Injection molding presses demonstrate this pattern.
Manufacturers of plastic toys process plastic molding powder,
and inject the plastic into molds of the desired shapes.
The class of toy (car, action figure, etc.) is determined by the
mold.
35
Advantages :
Decoupling the implementation of the product
from its use. “The code only deals with the
Product interface; therefore it can work with any
user-defined Concrete Product classes”.
Factory Method gives subclasses a hook for
providing an extended version of an object
Disadvantages :
The clients might have to subclass the Creator
class just to create a particular Concrete Product
object
1. If you have an inheritance hierarchy that exercises
polymorphism, consider adding a polymorphic
creation capability by defining a static factory method
in the base class.
2. Design the arguments to the factory method. What
qualities or characteristics are necessary and
sufficient to identify the correct derived class to
instantiate?
3. Consider designing an internal "object pool" that will
allow objects to be reused instead of created from
scratch.
4. Consider making all constructors private or protected.
37
The advantage of a Factory Method is that it can
return the same instance multiple times, or can
return a subclass rather than an object of that
exact type.
The new operator considered harmful. There is a
difference between requesting an object and
creating one. The new operator always creates an
object, and fails to encapsulate object creation. A
Factory Method enforces that encapsulation, and
allows an object to be requested without
inextricable coupling to the act of creation
38
E.g. create objects of different types
We can order a Car and get an
Aston Martin, MG, Jaguar etc
We don’t know which factory builds the car,
just that they implement CarFactory. Owner
has created the actual factory instance.
39
// we have a reference to owner
CarFactory aFactory = owner.makefactory();
Car myCar =aFactory.makeCar(“AstonMartin”);
class BritishFactory implements CarFactory{
public Car makeCar(String b) throws Exception {
if(b.equals(“AstonMartin”)) return new
AstonMartin();
else if (..) return ..;
else throw new Exception(b + “doesn’t
exist”);
}
}
40
Class AstonMartin extends Car {}
Class Jaguar extends Car {}
Interface CarFactory {
Public Car makeCar(String b) throws Exception;
}
41
Want portability to different window systems
◦ similar to multiple look-and-feel problem, but
different vendors will build widgets differently
Solution:
◦ define abstract class Window, with basic window
functionality (e.g., draw, iconify, move, resize, etc.)
◦ define concrete subclasses for specific types of
windows (e.g., dialog, application, icon, etc.)
◦ define WindowImp hierarchy to handle window
implementation by a vendor
42
43