Вы находитесь на странице: 1из 12

Apex T. G. India Pvt.

Ltd
Singleton Design Pattern
Design
Pattern(Day1)
1
Singleton

Singleton pattern restricts the instantiation of a


class and ensures that only one obof the class
exists in the ava virtual !achine.

It see!s to be a very si!ple design pattern but


"hen it co!es to i!ple!entation# it co!es "ith a
lot of i!ple!entation concerns.
1
Singleton

The i!ple!entation of Singleton pattern has


al"ays been a controversial topic a!ong
developers. So "e are providing so!e easiest "ay
to understand Singleton Design Pattern.

To i!ple!ent Singleton pattern# "e have di$erent


approaches but all of have so!e co!!on
concepts such as..
1
Singleton

Private constructor to restrict instantiation of the


class fro! other classes.

Private static variable of the sa!e class that is the


only obof the class.
1
Singleton

Public static !ethod that returns the obof the


class# this is the global access point for outer "orld
to get the obof the singleton class.

Di$erent approaches of Singleton pattern


i!ple!entation and design concerns "ith the
i!ple!entation%.
1
Singleton

&ager initiali'ation

Static bloc( initiali'ation

La'y Initiali'ation

Thread Safe Singleton

)sing *e+ection to destroy Singleton Pattern

&nu! Singleton

Seriali'ation and Singleton


1
Singleton
&ager initiali'ation,

obof Singleton -lass is created at the ti!e of class


loading# this is the easiest !ethod to create a
singleton class but it has a dra"bac( that obis
created even though client application !ight not
be using it.

)se only "hen Singleton class is not using a lot of


resources.

It doesn.t provide option for &xception handling.


1
Singleton

public class )seSingleton 0

private static 1nal )seSingleton us2 ne" )seSingleton 345

66private constructor to avoid client applications to use


constructor
private )seSingleton 3407

public static )seSingleton get8b340


return us5
7
7
1
Singleton3Static4
Static initiali'ation,

Static bloc(initiali'ation i!ple!entation is si!ilar


to eager initiali'ation# except that obof class is
created in the static bloc( that provides option
forexception handling.

9oth eager : static bloc( initiali'ation creates the


obeven before it.s being used and that is not the
best "ay to use it.
1
Singleton

public class )seSingleton 0


private static )seSingleton ob5
private )seSingleton3407
66static bloc( initiali'ation for exception handling
static0
try0
ob2 ne" )seSingleton345
7catch3&xception e40
thro" ne" *unti!e&xception3;&xception occured in creating
singleton obect;45
7
7
public static )seSingleton get8bect340
return ob5
7
7
1
-ontact us
Thanks
facebook.com/apex.tgi
twitter.com/ApextgiNoida
pinterest.com/apextgi
Stay Connected with us for more chapters on JAVA

Вам также может понравиться