Professional Documents
Culture Documents
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)
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: 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(){}
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