You are on page 1of 53

Creational

Patterns
Rao Nadeem

1
Overvie
w
• Creational
Patterns
– Factory
– Factory Method
– Abstract Factory
– Singleton
– Prototype
– Builder
– Object Pool
2
Factory
Method

3
Inten
t
• Defines an interface for creating objects,
but let subclasses to decide which class to
instantiate
• Refers to the newly created object through
a common interface
• The Factory Method Pattern is also
known as Virtual Constructor.

4
Exampl
e

5
6
Pizza Store (Without Factory
Pattern)

7
Example (Factory
Method)

8
Participant
• Product definessthe interface for objects
the factory method creates.
• ConcreteProduct implements the
Product interface.
• Creator (also refered as Factory because it
creates the Product objects) declares the
method FactoryMethod, which returns a
Product object.
• Creator relies on its subclasses to define the
factory method so that it returns an instance of
the appropriate ConcreteProduct.
• ConcreteCreator overrides the generating
method for creating ConcreteProduct objects
9
Cod
public interface Product { � }
e Product { �
public class ConcreteProduct implements
}
public abstract class Creator { Abstract
public void anOperation() { Factory
Product product =
factoryMethod();
}
protected abstract Product Concrete
ConcreteCreator extends Creator { protected Factory
factoryMethod();
public class
Product
} factoryMethod() {
return new ConcreteProduct();
}
}
public class Client
{ public static void main( String arg[] ) { Subclass
Creator creator = new specifies
object creation
ConcreteCreator();
creator.anOperation();
} } 10
Factory Method
(Example)

• Framework for Desktop Application


• Operations such as opening, creating
and saving a document
11
Cod
e be in MyApplication
//Following method will
Class public Document CreateDocument(){
return new MyDocument();
}

//Following method will be in Application


Class public void NewDocument(){
Document
doc=CreateDocument();
Docs.add(doc);
doc.Open(); 12
Advantages
• Factory Method Pattern allows the sub-
classes to choose the type of objects to
create.
• 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.

13
Usag
e
• When a class wants that its sub-classes
specify the objects to be created.
• When the parent classes choose the
creation of objects to its sub-classes.
• If the classes doesn't extend common
base class or interface they can not be
used in a factory method design
template.

14
Questions
?
• What’s the advantage of the Factory
Method Pattern when you only have one
ConcreteCreator?
– Decoupling the implementation of the
product from its use.
– If you add additional products or change a
product’s implementation, it will not affect your
Creator (because the Creator is not tightly
coupled to any ConcreteProduct).

15
Abstract Factory
Pattern

16
17
Abstract
Factory
• Define an interface or abstract class for
creating families of related (or dependent)
objects but without specifying their concrete
sub-classes.
• Abstract Factory lets a class returns a factory
of classes. So, this is the reason that Abstract
Factory Pattern is one level higher than the
Factory Pattern.
• This factory is also called as factory of factories
or Kit.
18
Abstract Factory
(Example)

19
Participant

s
AbstractFactory - declares an interface
for operations that create abstract
products.
• ConcreteFactory - implements operations
to create concrete products.
• AbstractProduct - declares an interface for a
type of product objects.
• Product - defines a product to be created by
the corresponding ConcreteFactory; it
implements the AbstractProduct interface.
• Client - uses the interfaces declared by the
AbstractFactory and AbstractProduct
classes. 20
21
Abstract Factory
Example

22
Participant
• Create Shape andsColor interfaces and concrete
classes implementing these interfaces.
• Create an abstract factory class AbstractFactory
as next step.
• Factory classes ShapeFactory and ColorFactory are
defined where each factory extends
AbstractFactory.
• A factory creator/generator class FactoryProducer
is created.
• AbstractFactoryPatternDemo, the demo class
uses FactoryProducer to get a AbstractFactory
object. It will pass information (CIRCLE /
RECTANGLE / SQUARE for Shape) to
AbstractFactory to get the type of object it needs. It
also passes information (RED / GREEN / BLUE for
Color) to AbstractFactory to get the type of object it
needs. 23
Code (Step
1)Shapes.
//Create an interface for
public interface Shape { void
draw(); }
//Create concrete classes
implementing the same interface.
public class Rectangle implements
Shape {
@Override public void draw()
{ System.out.println("Inside Rectangle::draw()
method.");
}
}
public class Square implements Shape
{ @Override public void
draw() {
System.out.println("Inside
Square::draw() method.");
} 24
Code (Step
//Create an interface for 2)
Color.
public interface Color { void
fill(); }
//Create concrete classes
implementing the same
interface.
public class Red implements
Color {
@Override public void fill()
{ System.out.println("Inside Red::fill()
method.");
}
}
public class Green implements Color
{ @Override public void
System.out.println("Inside
fill() { Blue::fill()
method.");
System.out.println("Inside
} }Green::fill() method.");
}
25
Code (Step
3)
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape)
;
}
public class ShapeFactory extends AbstractFactory
{
@Override
public Shape getShape(String shapeType)
{ if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}
else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
@Override
Color getColor(String color) {
return
} null;
}
26
Code (Step
3)
public class ColorFactory extends AbstractFactory
{ @Override public Shape getShape(String
shapeType){ return null;
}
@Override Color getColor(String color)
{ if(color == null){ return null; }
if(color.equalsIgnoreCase("RED")){
return new Red(); }
else if(color.equalsIgnoreCase("GREEN")){
return new Green(); }
else if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
}
27
Code (Step
4)
public class FactoryProducer {
public static AbstractFactory
getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE"))
{ return new ShapeFactory(); }
else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
28
Code (Step
5) args) {
public class AbstractFactoryPatternDemo
{ public static void main(String[]
//get shape factory
AbstractFactory shapeFactory =
FactoryProducer.getFactory("SH
APE");
Shape shape1 =
shapeFactory.getShape("CIRCLE"
);
shape1.draw();
Shape shape2 =
shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
//get color factory
AbstractFactory colorFactory =
FactoryProducer.getFactory("COLOR"); Color color1 =
colorFactory.getColor("RED");
color1.fill();
Color color2 =
colorFactory.getColor("Green"); color2.fill(); 29
Advantage
s
• Abstract Factory Pattern isolates the client
code from concrete (implementation)
classes.
• It eases the exchanging of object families.
• It promotes consistency among objects.

30
Usag
• e
When the system needs to be independent
of how its object are created, composed,
and represented.
• When the family of related objects has to be
used together, then this constraint needs to be
enforced.
• When you want to provide a library of
objects that does not show implementations
and only reveals interfaces.
• When the system needs to be configured
with one of a multiple family of objects.

31
Compariso
• Factory
n
• Factory Method
• Abstract
Factory

32
Simple
Factory

Factory
Method

33
Abstract
Factory

34
Factory
Pattern

• Step One: you call a method in the factory. Here it makes


sense to use a static method. The parameters for
your call tell the factory which class to create.
• Step Two: the factory creates your object. The only thing to
note is that of all the objects it can create, the objects have the
same parent class, or implement the same interface.
• Step Three: factory returns the object, and this is why step two
makes sense. Since the client didn't know what was going to be
returned, the client is expecting a type that matches the parent
class /interface.
35
Factory Method
Pattern

• Step One: the client maintains a reference to the abstract Creator, but instantiates it with
one of the subclasses. (i.e. Creator c = new ConcreteCreator1();
• Step Two: the Creator has an abstract method for creation of an object, which we'll call
"Create". It's an abstract method which all child classes must implement. This abstract
method also stipulates that the type that will be returned is the Parent Class or the
Interface of the “product”.
• Step Three: the concrete creator creates the concrete object. In the case of Step One, this
would be "Child Class A".
• Step Four: the concrete object is returned to the client. Note that the client doesn’t
really know what the type of the object is, just that it is a child of the parent.
36
Abstract Factory
Pattern An Abstract
Factory is
used
to create a
family of related
products

• Step One: the client maintains a reference to an abstract Factory class, which
all Factories must implement. The abstract Factory is instantiated with a
concrete factory.
• Step Two: the factory is capable of producing multiple types. This is where the
“family of related products” comes into play. More than one createMethods
which return multiple products.
• Step Three: the concrete factory creates the concrete objects.
• Step Four: the concrete objects are returned to the client. Again, the client
doesn’t really know what the type of the objects are, just that are a children of
the parents. 37
Summar
• y have in common is that
The thing that all three
they are responsible for creating objects.
• The calling class (which we call the “client”) wants an
object, but wants the factory to create it. You could
say that factories are used to encapsulate
instantiation.
• A Simple factory is normally called by the client via a
static method, and returns one of several objects
that all inherit/implement the same parent.
• The Factory Method design is really all about a
“create” method that is implemented by sub classes.
• Abstract Factory design is about returning a family
of related objects to the client. It normally uses
the Factory Method to create the objects. 38
Singleton
Pattern

39
Singleton

Pattern
Singleton Pattern says that just "define a class that
has only one instance and provides a global point
of access to it".
• In other words, a class must ensure that only
single instance should be created and single
object can be used by all other classes.
• There are two forms of singleton design pattern
– Early Instantiation: creation of instance at load time.
– Lazy Instantiation: creation of instance when
required.

40
UML of Singleton
Pattern

41
How to create Singleton
design pattern?
• Static member:
– It gets memory only once because of static, it
contains the instance of the Singleton class.
• Private constructor:
– It will prevent to instantiate the Singleton class
from outside the class.
• Static factory method:
– This provides the global point of access to the
Singleton object and returns the instance to the
caller.
42
Early Instantiation of Singleton
Pattern
• In such case, we create the instance of the class at
the time of declaring the static data member, so
instance of the class is created at the time of
classloading.
class Singleton{
private static Singleton uniqueinstance=new
Singleton();
//Early, instance will be created at load time
private Singleton(){}

public static Singleton get Singleton(){


return uniqueinstance;
}
}
43
Lazy Instantiation of Singleton
Pattern
• In such case, we create the instance of the class in synchronized
method or synchronized block, so instance of the class is created when
required.
class Singleton{
private static Singleton uniqueinstance; Check for an instance and if there
private Singleton(){} isn’t
one, enter a synchronized block.
public static Singleton get Singleton()
{ if (uniqueinstance == null){ Once in the block, check again and
synchronized (Singleton.class) if still null, create an instance.
{
if (uniqueinstance == null){
System.out.println("First time getInstance was
invoked!"); uniqueinstance = new Singleton();
}
}
return uniqueinstance;
}}}
public void doSomething()
{
... } }
Public class client{
Public static void main (String arg[]{
Singleton.getSingleton().doSomething();
}}
44
Singleton

Pattern
Advantage of Singleton design pattern
– Saves memory because object is not created at
each request.
– Only single instance is reused again and again.
• Usage of Singleton design pattern
– It is used in logging, caching, thread
pools, configuration settings, device
drivers etc.
– If we were to instantiate more than one we’d run
into all sorts of problems like incorrect program
behavior, overuse of resources, or inconsistent
results.
45
Applicability &

Examples
Logger Classes
– The Singleton pattern is used in the design of logger
classes.
– These classes are usually implemented as singletons,
and provide a global logging access point in all the
application components without being necessary to
create an object each time a logging operation is
performed.
• Configuration Classes
– The Singleton pattern is used to design the classes
which provide the configuration settings for an
application.
– By implementing configuration classes as Singleton not
only that we provide a global access point, but we also
keep the instance we use as a cache object.
– 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 46
Applicability &

Examples
Accesing resources in shared mode
– It can be used in the design of an application that needs to
work
with the serial port.
– Let's say that there are many classes in the application,
working in a multi-threading environment, which needs to
operate actions on the serial port.
– In this case a singleton with synchronized methods could be
used to manage all the operations on the serial port.
• Factories implemented as Singletons
– Let's assume that we design an application with a factory to
generate new objects(Acount, Customer, Site, Address
objects) with their ids, in a multithreading environment.
– If the factory is instantiated twice in 2 different threads then
is possible to have 2 overlapping ids for 2 different objects.
– If we implement the Factory as a singleton we avoid this
problem. Combining Abstract Factory or Factory Method
and Singleton design patterns is a common practice.
47
Specific problems and
•implementation
Thread-safe implementation for multi-
threading use.
– A singleton implementation should work in
any conditions.
– This is why we need to ensure it works when
multiple threads uses it.
• Early instantiation using implementation
with static field
– Singleton object is instantiated when the class is
loaded and not when it is first used, due to the
fact that the instance member is declared static.
– We don't need to synchronize any portion of the
code in this case. The class is loaded once this
guarantee the uniqueness of the object.

48
Specific problems and
•implementation
Serialization
– If the Singleton class implements the
java.io.Serializable interface, when a singleton is
serialized and then deserialized more than once,
there will be multiple instances of Singleton created.
– In order to avoid this the readResolve method
should be implemented.
– Serialization -: Turn object into a stream of bytes
– Deserialization - Turn a stream of bytes back into
a copy of the original object.
public class Singleton implements Serializable
{ protected Object readResolve() {
return getInstance();
}
}
49
Questions
• Does Singleton?violate SRP?
– Yes. Class has two responsibilities
• Manage its own instance
• Main role of the class
– But advantage is obvious and it is widely used.
• Can we subclass Singleton?
– You can’t extend a class with a private
constructor. So, the first thing you’ll have to do is
change your constructor so that it’s public or
protected.
– But then, it’s not really a Singleton
anymore, because other classes can 50
Question
• s are worse than
Why global variables
a Singleton?
– Intent of the pattern: to ensure only one
instance of a class exists and to provide global
access.
– A global variable can provide the global
access, but can not ensure only one instance.

51
Assignment
1
• Factory, Factory Method and Abstract
Factory.
– Find and discuss some scenarios where
these patterns can be applied.
– Illustrate with UML diagrams.
– Deadline is 2 Weeks

52
Reference
s
• http://www.oodesign.com/
• http:/ /www.javatpoint.com/design-pattern
s- in-java
• https://www.tutorialspoint.com/design_patte

rn/
• Design Patterns, Elements of Reusable
Object- Oriented Software. (Book)
• Head First Design Patterns (Book)
53

You might also like