Software component
design
Chapter Two
Creational Design
Patterns
27/01/2025 creational design patterns 1
Creational design
patterns
Objectives
Describe creational design pattern and the two
types of it.
Discuss types of creational design patterns, the
intent of each design pattern, application area of
each design pattern and its pros and cons.
Give real world examples for each creational
design pattern and show with sample codes
Apply those creational design patterns in different
situations when you are developing software
systems and applications
27/01/2025 creational design patterns 2
Creational design
patterns
Deals with object creation and initialization,
providing guidance about which objects are
created for a given situation.
Are concerned with the way of creating objects.
These patterns can be further categorized into
o Class-creation patterns use inheritance
effectively in the instantiation process,
o Object-creation patterns use delegation
effectively to get the job done.
27/01/2025 creational design patterns 3
Creational design
patterns…
Types of creational design patterns
o Singleton
o Factory Method
o Abstract Factory
o Prototype
o Builder
o Object pool
27/01/2025 creational design patterns 4
1. singleton design
pattern
It ensures that at most only one instance of an
object exists throughout application.
It 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
o Early Instantiation - creation of instance at load time.
o Lazy Instantiation - creation of instance when
required.
27/01/2025 creational design patterns 5
1. singleton design
pattern…
Characteristics of Singleton pattern
o They are static in nature
o Private constructor
o Private instance of class
o No parameter to the constructor
27/01/2025 creational design patterns 6
1. singleton design
pattern…
Pattern name: Singleton pattern
Problem: How can we guarantee that one and
only one instance of a class can be created?
Solution: Create a class with a class operation
getInstance().
o On subsequent calls of getInstance(), no new
instance is created, but identity of existing
object is returned.
27/01/2025 creational design patterns 7
1. singleton design
pattern…
Application areas
Use Singleton Design Pattern when
o Resources that are expensive to create (like
database connection objects)
o Classes which provide access to configuration
settings for the application
o Classes that contain resources that are
accessed in shared mode
o It's good practice to keep all loggers as
Singletons which increases performance
27/01/2025 creational design patterns 8
1. singleton design
pattern…
Singleton structure
27/01/2025 creational design patterns 9
1. singleton design
pattern…
Singleton patterns participants
Singleton
o Declare all constructors private and provide
only one entry for obtaining a reference to the
sole instance.
Client
o Clients can get to the sole instance of Singleton
by asking Singleton to return a reference to it.
Collaborations
o A client can only call getInstance() to get a ref-
erence to the sole instance.
o A client cannot create any instance of Singleton
27/01/2025 creational design patterns 10
1. singleton design
pattern…
,
27/01/2025 creational design patterns 11
1. singleton design
pattern…
Sample code..
Step 1
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
27/01/2025 creational design patterns 12
1. singleton design
pattern…
Sample code..
Step 2
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not
visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();
}}
Step3
Hello World!
27/01/2025 creational design patterns 13
2. Factory method
design pattern
It define an interface or abstract class for creating
an object without specifying their concrete
classes.
Subclasses are responsible to create the instance
of the class.
Define an interface for creating an object, but let
subclasses decide which class to instantiate
also called Virtual Constructor.
Factory Method lets a class defer instantiation to
subclasses.
The new operator considered harmful.
27/01/2025 creational design patterns 14
2. Factory method
design pattern
Name : Factory method
Problem : A framework with abstract application
classes and application-specific subclasses to in-
stantiate to realize different implementations
Solution : The Factory Method pattern encapsu-
lates the knowledge of which subclass to create
and moves this knowledge out of the framework.
27/01/2025 creational design patterns 15
2. Factory method
design pattern…
Example
Suppose you want to create multiple instances of
similar kind and want to achieve loose coupling
then you can go for Factory pattern.
A class implementing factory design pattern
works as a bridge between multiple classes.
Consider an example of using multiple database
servers like SQL Server and Oracle.
If you are developing an application using SQL
Server database as backend, but in future need to
change backend database to oracle, you will need
to modify all your code, if you haven’t written
your code by factory
27/01/2025 design
creational pattern.
design patterns 16
2. Factory method
design pattern…
Example….
Imagine that you’re creating a logistics
management application. The first version of your
app can only handle transportation by trucks, so
the bulk of your code lives inside the Truck class.
After a while, your app becomes pretty popular.
Each day you receive dozens of requests from sea
transportation companies to incorporate sea
logistics into the app.
Use the Factory Method pattern when
A class can't anticipate the class of objects it
must create.
A class wants its subclasses
27/01/2025 to specify the objects17
creational design patterns
2. Factory method
design pattern…
Example
Create the UML diagram and write the source code for factory
pattern with supper class of Shape having three sub class
(Rectangle, Circle and Square). ShowMessage methods should
be included in super class, the sub class also inherit these
methods from the interface class. The shapeFactory class cre-
ate the object and the out put also displayed by ShapeFacto-
ryMain class. (Using Interface and abstract class)
27/01/2025 creational design patterns 18
2. Factory method
design pattern…
Sample example UML diagram
27/01/2025 creational design patterns 19
2. Factory method
design pattern…
Exercise 1
1. Create the UML diagram and write the source code for factory pat-
tern with supper class of Pollygon having three sub class (Triangle,
quadrilateral and pentagon). A PolygonFactory will be used to
fetch objects from this family: (Using Abstract Class and interface)
2. Differentiate the two creational pattern (Singleton and factory
method) with real world example by your own word.
3. Draw the UML diagram(sequence and collaboration) for the exam-
ple in question 2 and implement it by using abstract class (for fac-
tory method) and synchronized method (for singleton
pattern)
4. Can we say singleton is a factory method design pat-
tern? If yes where?
27/01/2025 creational design patterns 20
3. Abstract factory
design pattern…
It defines an interface or abstract class to
produce families of related or dependant objects
without specifying their concrete classes.
Abstract Factory pattern is almost similar to
Factory Pattern except the fact that its more
like factory of factories.
It is also called Kit.
In the Abstract Factory pattern, we get rid of if-
else block and have a factory class for each sub-
class. Then an Abstract Factory class that will
return the sub-class based on the input factory
class.
27/01/2025 creational design patterns 21
3. Abstract factory
design pattern…
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 products.
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.
27/01/2025 creational design patterns 22
3. Abstract factory
design pattern…
Advantages
It provides approach to code for interface rather
than implementation.
It is “factory of factories” and can be easily
extended to accommodate more products.
It is robust and avoid conditional logic of Factory
pattern.
Open/Closed Principle
Dis advantages
The code may become more complicated than it
should be, since a lot of new interfaces and classes
are introduced along with the pattern.
27/01/2025 creational design patterns 23
3. Abstract factory
design pattern…
Exercise : Sample UML diagram (write a
source code)
27/01/2025 creational design patterns 24
3. Builder design
pattern…
It means construct a complex object from simple objects
using step-by-step approach.
It is useful when a creational algorithm of a complex
object is independent of the assembly of the parts of the
object.
The construction process is also capable of building a
different representation of that object under consideration
Builder pattern was introduced to solve some of the
problems with Factory and Abstract Factory design
patterns when the Object contains a lot of attributes.
Example
To create a computer, different parts are assembled
depending upon the order received by the customers
27/01/2025 creational design patterns 25
4. Builder design
pattern…
Use the Builder pattern when
The algorithm for creating a complex object should
be independent on the parts that make up the object
and how they're assembled.
The construction process must allow different
representations for the object that's constructed.
Advantages
It provides clear separation between the construction
and representation of an object.
It provides better control over construction process.
It supports to change the internal representation of
objects.
27/01/2025 creational design patterns 26
4. Builder design
pattern…
Let’s see how we can implement builder design pattern in java.
First of all you need to create a static nested class and then copy
all the arguments from the outer class to the Builder class. We
should follow the naming convention and if the class name
is Computer then builder class should be named
as ComputerBuilder.
Java Builder class should have a public constructor with all the
required attributes as parameters.
Java Builder class should have methods to set the optional
parameters and it should return the same Builder object after
setting the optional attribute.
The final step is to provide a build() method in the builder class
that will return the Object needed by client program. For this we
need to have a private constructor in the Class with Builder class
as argument.
27/01/2025 creational design patterns 27
4. Builder design
pattern…
Real world example 1
For creating bank account, it contains different data/information
like account number, full name, email, phone, address….
public class BankAccount {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
// constructors/getters
public static class BankAccountBuilder {
// builder code
}
}
27/01/2025 creational design patterns 28
4. Builder design
pattern…
public static class BankAccountBuilder {
private String name, accountNumber, email;
private boolean newsletter;
public BankAccountBuilder(String name, String accountNumber) {
this.name = name;
this.accountNumber = accountNumber; }
public BankAccountBuilder withEmail(String email) {
this.email = email;
return this; }
public BankAccountBuilder wantNewsletter(boolean newsletter) {
this.newsletter = newsletter;
return this; }
public BankAccount build() {
return new BankAccount(this);
}}
27/01/2025 creational design patterns 29
4. Builder design
pattern…
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("
[email protected]")
.wantNewsletter(true)
.build();
Real world example 2…
For example, let’s think about how to create a House object.
To build a simple house, you need to construct four walls
and a floor, install a door, fit a pair of windows, and build a
roof. But what if you want a bigger, brighter house, with a
backyard and other goodies (like a heating system,
plumbing, and electrical wiring)?
27/01/2025 creational design patterns 30
4. Builder design
pattern…
Real world example 2
We are considering a business case of pizza-hut
where we can get different varieties of pizza and
cold-drink.
Pizza can be either a Veg pizza or Non-Veg pizza
of several types (like cheese pizza, onion pizza,
masala-pizza etc) and will be of 4 sizes i.e. small,
medium, large, extra-large.
Cold-drink can be of several types (like Pepsi,
Coke, Dew, Sprite, Fanta, Maaza, Limca, Thums-
up etc.) and will be of 3 sizes small, medium,
large.
27/01/2025 creational design patterns 31
4. Builder design
pattern…
Exercise : UML example for the above example and write the
source code
27/01/2025 creational design patterns 32
5. Prototype design
pattern…
It provides a mechanism to copy the original Object to
a new Object and then modify it according to our
needs.
o This pattern uses Java cloning to copy the Object.
Example 2
Suppose we have a master copy of a valuable docu-
ment. We need to incorporate some changes to it to
see the effect of the change. In such a case, we can
make a photocopy of the original document and edit
the changes
27/01/2025 creational design patterns 33
5. Prototype design
pattern…
Use the Prototype pattern when
When the classes are instantiated at runtime.
When the cost of creating an object is expensive or
complicated.
When you want to keep the number of classes in an
application minimum.
When the client application needs to be unaware of
object creation and representation.
When to avoid building a class hierarchy of factories
that parallels the class hierarchy of products
When instances of a class can have one of only a few
different combinations of state.
27/01/2025 creational design patterns 34
5. Prototype design
pattern…
Advantages
Reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing
which type of object it will be.
It lets you add or remove objects at runtime.
Dis advantages
It is built on the method .clone(), which could be
complicated sometimes in terms of shallow copy and
deep copy.
Moreover, classes that have circular references to
other classes cannot really be cloned.
27/01/2025 creational design patterns 35
5. Prototype design
pattern…
Example 1
Suppose we have an Object that loads data from
database. Now we need to modify this data in our
program multiple times, so it’s not a good idea to
create the Object using new keyword and load all
the data again from database. The better
approach would be to clone the existing object
into a new object and then do the data
manipulation.
27/01/2025 creational design patterns 36
5. Prototype design
pattern…
Example 1…. UML diagram
27/01/2025 creational design patterns 37
5. Prototype design
pattern…
Example 1
import java.util.ArrayList;
import java.util.List;
public class Employees implements Cloneable{
private List<String> empList;
public Employees(){
empList = new ArrayList<String>();
}
public Employees(List<String> list){
this.empList=list;
}
27/01/2025 creational design patterns 38
5. Prototype design
pattern…
Example 1…
public void loadData(){
//read all employees from database and put into the list
empList.add("Pankaj");
empList.add("Raj");
empList.add("David");
empList.add("Lisa");}
public List<String> getEmpList() {
return empList; }
@Override
public Object clone() throws CloneNotSupportedException{
List<String> temp = new ArrayList<String>();
for(String s : this.getEmpList()){
temp.add(s);
}
return new Employees(temp);
} }
27/01/2025 creational design patterns 39
5. Prototype design
pattern…
Example 1…
public class PrototypePatternTest {
public static void main(String[] args) throws CloneNotSupportedException {
Employees emps = new Employees();
emps.loadData();
//Use the clone method to get the Employee object
Employees empsNew = (Employees) emps.clone();
Employees empsNew1 = (Employees) emps.clone();
List<String> list = empsNew.getEmpList();
list.add("John");
List<String> list1 = empsNew1.getEmpList();
list1.remove("Pankaj");
System.out.println("emps List: "+emps.getEmpList());
System.out.println("empsNew List: "+list);
System.out.println("empsNew1 List: "+list1);
}
}
27/01/2025 creational design patterns 40
Summery (Creational
design patterns)
General UML
27/01/2025 creational design patterns 41
Summery (Creational
design patterns)
General UML
27/01/2025 creational design patterns 42
Summery (Creational
design patterns)
General UML
27/01/2025 creational design patterns 43
Summery (Creational
design patterns)
Abstract Factory - Creates an instance of several families of
classes
Builder - Separates object construction from its representation
Factory Method - Creates an instance of several derived classes
Object Pool - Avoid expensive acquisition and release of
resources by recycling objects that are no longer in use
Prototype - A fully initialized instance to be copied or cloned
Singleton - A class of which only a single instance can exist
Prototype doesn't require sub classing, but it does require an
Initialize operation. Factory Method requires sub classing, but
doesn't require Initialize.
Factory Method: creation through inheritance. Prototype:
creation through delegation.
27/01/2025 creational design patterns 44
Summery (Creational
design patterns)…
Many designs start by using Factory Method (less complicated and
more customizable via subclasses) and evolve toward
Abstract Factory, Prototype, or Builder (more flexible, but more
complicated).
Builder focuses on constructing complex objects step by step.
Abstract Factory specializes in creating families of related
objects. Abstract Factory returns the product immediately,
whereas Builder lets you run some additional construction steps before
fetching the product.
Abstract Factory classes are often based on a set of
Factory Methods, but you can also use Prototype to compose the
methods on these classes.
Abstract Factories, Builders and Prototypes can all be
implemented as Singletons.
Abstract Factory classes are often implemented with
Factory Methods, but they can also be implemented using
Prototype.
27/01/2025 creational design patterns 45
Creational design
patterns
Any Questions ?
27/01/2025 creational design patterns 46