Singleton Design Pattern Note by Udhayakumar
Singleton Design Pattern Note by Udhayakumar
an
solutions to common software design problems
Well established
23 diff DP
four Design Patterns
lyof
a Gang of
sure
very common in
10 important design patterns Very commonly
asked in
interviews
Why learn
DP
Shared vocabulary
also saves a lot of time
interviews
very imp for
Types of
Eng Patterns
Singleton
DP
0M
Creational Design Patterns
F Builder DIS simple factory
factory factory method
Abstractfactory
How an object is
created prototype
How many objectsto be created
can be created
X E
b
new x c
object
F
X new x 1
tx
WII
shared resource behind the scenes
case which is having
a
A
Power DB connection
Url
d
Md username
1 dbsome
db execute
C hÉ7wn
be DBC
DBconnectiond mm it
Im
g
Userlemia Orderservice
c L
perm
d
dbsavelli dbsaree
I
db event
C t 4 db executeC i
Moyosener
Resources
Memory
9
FEI
IIhire
dog
all do we need to do
dB c what thing
to create a
wasteof time
A B
Database Connection
Mal d be dbs
change Url C I d bi chapeau
a Shared
Resource
Why is expensive and only I object
b Creation of an object
is needed
a
Commonfette
How to implement
I
string password
string username
his th connection pood
ly
connection
class Database
string are
I
string password
string username
dd
his th connection pood
class
1 of this
DatabaseConnection C E
private
1
constructor private
We need to keep
PI create I object
But we need to constructor
an object we
need to call
But to create
same class
I can call private constructor from
connection
class Database
string are
I
string password
string username
his th connection pood
1
DatabaseConnection C
private
1
I 1 return DBL
string are
I I
string password
string username
histhlonnection pood
1 DBC instance
a null
private Iic
I
Dbe pity
I
j
null E
publish
if instance
instance new Discos
jij.gg F
lg Clients client I
f f Inane l
createInstanceC
DBCdbs
new DBC Y
Ibe sanch
Steps
n
create an instance
create static method to
a
is already created
cheeks if the instance
Static method
return instance
If yes instance and return
else create new
DBL
create instances
instance null
if instance new DBC
returninstance
M T2
1
static createInstance CK
public
return instance
f I
App startup
will be slower
Cons instance
Can't give variable config while creating the first
Create singleton at Runtime
We can use locks
class DBC E
13124
private D
createInstance C
static DBC
public synchronized
I instance mel
if new DBC
instance
I Ireturn instance
To different places
th
Wh
perf is slow
way
mm
MEI X me
E1t
m
mel
if I instance
if l instance andM
instance new Disco lock C
I I instance new DBC
unlocks 7
Unlock y
return instance return instance
H creates on
A matesobj
DCL
Double check hacking
Tinkler nuuk
linetame
if instance new DBCc
1
I
Unlock
T2
99.97 cares Goadformance