Design Patterns
What is Design Patterns
●
Design patterns are typical solutions to
commonly occurring problems in software
design.
●
They are like pre-made blueprints that you can
customize to solve a recurring design problem
in your code
●
It is a description or template for how to solve a
problem that can be used in many different
situations.
Design Patterns
●
Patterns deal with
●
Application and system design
●
Abstractions on top of code
●
Speed up the development process by providing tested,
proven development paradigms.
●
Relationships between classes and other collaborators
●
Problems that have been already solved
Design Patterns
●
Patterns are not concerned with
●
Algorithms
●
Specific implementations or classes
Design Patterns
(Category)
●
Creational patterns provide object creation
mechanisms that increase flexibility and reuse
of existing code.
●
Structural patterns explain how to assemble
objects and classes into larger structures, while
keeping the structures flexible and efficient.
●
Behavioral patterns take care of effective
communication and the assignment of
responsibilities between objects.
Singleton Pattern
Singleton Pattern
●
Intent
●
A creational design pattern that ensures only
one instantation (of the class) is created and
avoids creating multiple instances of the same
object.
●
Provides a global access point to this instance.
●
Problem
●
Application needs one, and only one, instance
of an object. Additionally, lazy initialization and
global access are necessary.
Singleton Pattern
Instantiate Objects from Main Class
Output of Main Class
Singleton Pattern
Instantiate Objects from Main Class
Output of Main Class
Advantages
●
The Singleton pattern solves two problems at the
same time, violating the Single Responsibility
Principle:
1) Ensure that a class has just a single instance.
2) Provide a global access point to that
instance.
Implementing Singleton
●
Declare a static variable of object itself
Implementing Singleton
●
Make the default constructor private, to prevent
other objects from using the new operator with
the Singleton class.
Implementing Singleton
●
Create a static creation method that acts as a
constructor. Under the hood, this method calls
the private constructor to create an object and
saves it in a static field. All following calls to this
method return the cached object.
Lazy Initialization
Main Class
Output
Singleton Pattern
(Structure)
THANK YOU