CREATIONAL DESIGN PATTERNS
Software Design Patterns
FAKHRELDIN ALI
[Link]@[Link]
CREATIONAL DESIGN PATTERNS
Creating a collection of objects in flexible ways.
Creational patterns provide various object creation mechanisms,
which increase flexibility and reuse of existing code.
DESIGN PATTERNS 2
CREATIONAL PATTERNS
Factory Method:
Provides an interface for creating objects in a superclass, but allows subclasses to
alter the type of objects that will be created.
Abstract Factory:
Factory for building related objects
Builder:
Factory for building complex objects incrementally
Prototype:
Factory for cloning new instances from a prototype
Singleton:
Factory for a singular (sole) instance
SINGLETON
The government is an excellent example of the Singleton
pattern.
A country can have only one official government. Regardless
of the personal identities of the individuals who form
governments, the title,“The Government of X”, is a global point
of access that identifies the group of people in charge.
DESIGN PATTERNS 4
SINGLETON
Design Purpose: Ensure that there is exactly one
instance of a class S. Be able to obtain the instance
from anywhere in the application.
Design Pattern Summary
Make the constructor of S private; define a private static attribute for S of
type S; define a public accessor for it.
Key Concept — Singleton Design Pattern
When a class has exactly one instance.
DESIGN PATTERNS 5
SINGLETON APPLICABILITY
Use the singleton pattern when
There must be exactly one instance of a class, and it must be accessible to client 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.
DESIGN PATTERNS 6
SINGLETON: CLASS MODEL
Client
Singleton Design Pattern
MyClass singletonOfMyClass
getSingletonOfMyClass(): MyClass
«static»
1
DESIGN PATTERNS 7
THE SINGLETON DESIGN PATTERN -- APPLIED TO
MYCLASS (CASE 1)
Define a private static member variable of MyClass of type MyClass
private static MyClass singletonOfMyClass = new MyClass();
Make the constructor of MyClass private
private MyClass() { /* …. constructor code …. */ };
Define a public static method to access the member
public static MyClass getSingletonOfMyClass()
{
return singletonOfMyClass;
}
DESIGN PATTERNS 8
SINGLETON DESIGN PATTERN EXAMPLE
(CASE 2)
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
public class SingletonInstantiator {
public SingletonInstantiator() {
ClassicSingleton instance = [Link]();
}
}
DESIGN PATTERNS 9
SINGLETON DESIGN PATTERN
Key Concept — Singleton Design Pattern
When a class must have exactly one instance, make the
constructor private and the instance a private static
variable with a public accessor.
DESIGN PATTERNS 10
COMMENTS ON SINGLETON
This form of Singleton is simple but it creates the Singleton object even if the
object is never needed; this is wasteful if Singleton is large.
The idea of Singleton can be extended to the problem of having just two
instances of a class.
DESIGN PATTERNS 11
PROS AND CONS
DESIGN PATTERNS 12
BUILDER PATTERN
Builder is a creational design pattern that lets you construct complex objects step by
step. The pattern allows you to produce different types and representations of an
object using the same construction code.
DESIGN PATTERNS 13
BUILDER PATTERN
Problem
Imagine a complex object that requires laborious, step-by-step initialization of many
fields and nested objects. Such initialization code is usually buried inside a monstrous
constructor with lots of parameters. Or even worse: scattered all over the client
code.
DESIGN PATTERNS 14
BUILDER PATTERN
DESIGN PATTERNS 15
BUILDER PATTERN
The Builder pattern suggests that you extract the object construction code out of its
own class and move it to separate objects called builders.
The Builder pattern lets you construct complex objects step by step.
The Builder doesn’t allow other objects to access the product while
it’s being built.
DESIGN PATTERNS 16
BUILDER PATTERN
✓ The pattern organizes object construction into a set of steps (buildWalls, buildDoor,
etc.). To create an object, you execute a series of these steps on a builder object. The
important part is that you don’t need to call all of the [Link] can call only those
steps that are necessary for producing a particular configuration of an object.
✓ Some of the construction steps might require different implementation when you
need to build various representations of the product. For example, walls of a cabin
may be built of wood, but the castle walls must be built with stone.
✓ In this case, you can create several different builder classes that implement the same
set of building steps, but in a different manner. Then you can use these builders in the
construction process (i.e., an ordered set of calls to the building steps) to produce
different kinds of objects.
DESIGN PATTERNS 17
BUILDER PATTERN
For example, imagine a builder that builds everything from wood and glass, a second
one that builds everything with stone and iron and a third one that uses gold and
diamonds. By calling the same set of steps, you get a regular house from the first builder,
a small castle from the second and a palace from the third. However, this would only
work if the client code that calls the building steps is able to interact with builders
using a common interface.
Director
You can go further and extract a series of calls to the builder steps you use to
construct a product into a separate class called director. The director class defines the
order in which to execute the building steps, while the builder provides the
implementation for those steps.
DESIGN PATTERNS 18
BUILDER PATTERN STRUCTURE
DESIGN PATTERNS 19
BUILDER PATTERN APPLICABILITY
• Use the Builder pattern to get rid of a “telescoping constructor”.
say you have a constructor with ten optional parameters. Calling such a beast is very
inconvenient; therefore, you overload the constructor and create several shorter
versions with fewer [Link] constructors still refer to the main one, passing
some default values into any omitted parameters.
• Use the Builder pattern when you want your code to be able to create different
representations of some product (for example, stone and wooden houses).
• Use the Builder to construct Composite trees or other complex objects.
DESIGN PATTERNS 20
BUILDER PATTERN
DESIGN PATTERNS 21
FACTORY METHOD
Factory Method is a creational design pattern that provides an interface for creating
objects in a superclass, but allows subclasses to alter the type of objects that will
be created.
• 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.
DESIGN PATTERNS 22
FACTORY METHOD
• But how about the code? At present, most of your code is coupled to the Truck
class. Adding Ships into the app would require making changes to the entire
codebase. Moreover, if later you decide to add another type of transportation to
the app, you will probably need to make all of these changes again.
• As a result, you will end up with pretty nasty code, riddled with conditionals that
switch the app’s behavior depending on the class of transportation objects.
Solution
The Factory Method pattern suggests that you replace direct object construction
calls (using the new operator) with calls to a special factory method. Don’t worry:
the objects are still created via the new operator, but it’s being called from within
the factory method. Objects returned by a factory method are often referred to
as products.
DESIGN PATTERNS 23
FACTORY METHOD
DESIGN PATTERNS 24
FACTORY METHOD
EXAMPLE
DESIGN PATTERNS 25
FACTORY METHOD
Applicability
• Use the Factory Method when you don’t know beforehand the
exact types and dependencies of the objects your code should
work with.
• Use the Factory Method when you want to provide users of
your library or framework with a way to extend its internal
components.
• Use the Factory Method when you want to save system
resources by reusing existing objects instead of rebuilding
them each time.
DESIGN PATTERNS 26
FACTORY METHOD
DESIGN PATTERNS 27
ABSTRACT FACTORY
Abstract Factory is a creational design pattern that lets you produce families of
related objects without specifying their concrete classes.
DESIGN PATTERNS 28
ABSTRACT FACTORY
DESIGN PATTERNS 29
ABSTRACT FACTORY
• You need a way to create individual furniture objects so that they match other
objects of the same family. Customers get quite mad when they receive non-
matching furniture.
• Also, you don’t want to change existing code when adding new products or
families of products to the program. Furniture vendors update their catalogs very
often, and you wouldn’t want to change the core code each time it happens.
Solution
The first thing the Abstract Factory pattern suggests is to explicitly declare interfaces
for each distinct product of the product family (e.g., chair, sofa or coffee table). Then
you can make all variants of products follow those interfaces. For example, all chair
variants can implement the Chair interface; all coffee table variants can implement
the CoffeeTable interface, and so on.
DESIGN PATTERNS 30
ABSTRACT FACTORY
DESIGN PATTERNS 31
ABSTRACT FACTORY
The next move is to declare the Abstract Factory—an interface with a list of creation
methods for all products that are part of the product family (for example, createChair,
createSofa and createCoffeeTable). These methods must return abstract product types
represented by the interfaces we extracted previously: Chair, Sofa, CoffeeTable and so
on.
DESIGN PATTERNS 32
ABSTRACT FACTORY
Now, how about the product variants? For each variant of a product family, we create
a separate factory class based on the AbstractFactory interface. A factory is a class that
returns products of a particular kind. For example, the ModernFurnitureFactory can
only create ModernChair, ModernSofa and ModernCoffeeTable objects.
The client code has to work with both factories and products via their respective
abstract interfaces. This lets you change the type of a factory that you pass to the
client code, as well as the product variant that the client code receives, without
breaking the actual client code.
DESIGN PATTERNS 33
ABSTRACT FACTORY
DESIGN PATTERNS 34
PROTOTYPE CREATIONAL PATTERN
Prototype is a creational design pattern that lets you copy existing objects
without making your code dependent on
their classes.
Assignment # 1:
Read the text book from page 125- 137, and write summary about the pattern ,
submit the report by 8-10-2024 , using the e-learning portal
DESIGN PATTERNS 35
SUMMARY OF CREATIONAL PATTERNS
Use Creational Design Patterns when creating complex objects
Factory when creating individuals
Singleton for exactly one, safely
Abstract Factory when creating families
Builder
Prototype to “mix & match” ( reading Assignment)
DESIGN PATTERNS 36