You are on page 1of 13

Design Pattern:

If one Problem is arising again & again, we need to findout the Best Solution for
that problem.
For one problem, there might be 'N' number of solutions, But among all, there
might be only one 'Best Solution'.
Find that 'Best Solution', and Apply to the Partiular problem.
Suppose, one problem is ouring in our pro!et, "e need to identify the Best
Solution for that problem.
Identifying the Best Solution is alled as #$esign Pattern#.
%ne if u find the Best Solution for the '&eursi'e Problem', (eep using the same
solution )$esign pattern*.
Design Patterns are 'ery popular among software de'elopers. A design pattern is a
well desribed solution to a ommon software problem.
Some of the benefits of using design patterns are:
1. $esign Patterns are already defined and pro'ides industry standard approach
to sol'e a reurring problem, so it sa'es time if we sensibly use the
design pattern.
2. +sing design patterns promotes reusability that leads to more robust and
highly maintainable ode. It helps in reduing total ost of ownership
),-%* of the software produt.
.. Sine design patterns are already defined, it ma/es our ode easy to
understand and debug. It leads to faster de'elopment and new members of
team understand it easily.
,ypes of $esign Pattern 0
1111111111111111111111111
2. Singleton $esign Pattern
3. $oubleton $esign Pattern
.. Immutable $esign Pattern
1
1.Singleton Design Pattern:
Singleton pattern restrits the instantiation of a lass and ensures that only one
instane of the lass e4ists in the !a'a 'irtual mahine.
,he singleton lass must pro'ide a global aess point to get the instane of the
lass. Singleton pattern is used for logging, dri'ers ob!ets, ahing and thread
pool.
Singleton design pattern is also used in other design patterns li/e Abstrat
Fatory, Builder, Prototype,Faade et. Singleton design pattern is used in ore
!a'a lasses also,
for e4ample. !a'a.lang.&untime,!a'a.awt.$es/top.

Steps to create a singleton class:
2. $efine Pri'ate onstrutor to restrit instantiation of the lass from
other lasses.
3. $elare Pri'ate stati 'ariable of the same lass, that is the only
instane of the lass
.. Pro'ide a publi stati method that will return the singleton lass
instane 'ariable. If the 'ariable is not initiali5ed then initiali5e it or
else simply return the instane 'ariable.
,ypes of $esign Pattern 0
1111111111111111111111111111
1. 6ager initiali5ation
2. Stati blo/ initiali5ation
3. 7a5y Initiali5ation
4. ,hread Safe Singleton
1.Eager initialization:
In eager initiali5ation, the instane of Singleton -lass is reated at the time of
lass loading,
this is the easiest method to reate a singleton lass but it has a drawba/ that
instane is reated e'en though lient appliation might not be using it.
If your singleton lass is not using a lot of resoures, this is the approah to
use.
But in most of the senarios, Singleton lasses are reated for resoures suh as
File System, $atabase onnetions et and we should a'oid the instantiation until
unless lient alls the getInstane method. Also this method doesn8t pro'ide any
options for e4eption handling.
2
Example Program 1:
package singleton.6agerInitiali5edSingleton9
public class 6agerInitiali5edSingleton2 :
private int id9
private String name9
private static final 6agerInitiali5edSingleton2 instance ;
ne 6agerInitiali5edSingleton2)2<, #Sashi#*9
==pri'ate onstrutor to a'oid lient appliations to use onstrutor
private 6agerInitiali5edSingleton2)int id, String name* :
this.id ; id9
this.name ; name9
>
public static 6agerInitiali5edSingleton2 getInstane)* :
return instance9
>
?%'erride
public String toString)* :
return #6agerInitiali5edSingleton2 @id;# A id A #, name;# A name A #B#9
>
>
class Cgr2 :
public static void main)String@B args* :
6agerInitiali5edSingleton2 ob!2 ;
6agerInitiali5edSingleton2.getInstance)*9
6agerInitiali5edSingleton2 ob!3 ;
6agerInitiali5edSingleton2.getInstance)*9
System.out.println)#ob!2 0 # A ob!2*9
System.out.println)#ob!3 0 # A ob!3*9
System.out.println)#ob!2 ;; ob!3 0 # A )ob!2 ;; ob!3**9
>
>
!utput:
ob!2 0 6agerInitiali5edSingleton2 @id;2<, name;SashiB
ob!3 0 6agerInitiali5edSingleton2 @id;2<, name;SashiB
ob!2 ;; ob!3 0 true
3
". Static block initialization:
Stati blo/ initiali5ation implementation is similar to eager initiali5ation,
e4ept that instane of lass is reated in the stati blo/ that pro'ides option
for e4eption handling.
Both eager initiali5ation and stati blo/ initiali5ation reates the instane
e'en before it8s being used and that is not the best pratie to use
Example Program ":
package singleton9
public class StatiBlo/Singleton2 :
private int id9
private String name9
private double salary9
private static final StatiBlo/Singleton2 instance9
static :
instance ; ne StatiBlo/Singleton2)2<, #Sashi (umar#, 3<<<<.D<<*9
>
private StatiBlo/Singleton2)int id, String name, double salary* :
this.id ; id9
this.name ; name9
this.salary ; salary9
>
public static StatiBlo/Singleton2 getInstane)* :
return instance9
>

?%'erride
public String toString)* :
return #StatiBlo/Singleton2 @id;# A id A #, name;# A name
A #, salary;# A salary A #B#9
>
>
class Cgr3 :
public static void main)String@B args* :
StatiBlo/Singleton2 instane2 ; StatiBlo/Singleton2.getInstance)*9
StatiBlo/Singleton2 instane3 ; StatiBlo/Singleton2.getInstance)*9
System.out.println)#instane2 0 # A instane2*9
System.out.println)#instane3 0 # A instane3*9
System.out.println) #instane2 ;; instane3 0 #
A )instane2 ;; instane3**9
>
>
!utput:
ob!2 0 6agerInitiali5edSingleton2 @id;2<, name;SashiB
ob!3 0 6agerInitiali5edSingleton2 @id;2<, name;SashiB
ob!2 ;; ob!3 0 true
4
#. $azy %nitialization:
7a5y initiali5ation method to implement Singleton pattern reates the instane in
the global aess method.
,he below implementation wor/s fine inase of single threaded en'ironment but
when it omes to multithreaded systems, it an ause issues if multiple threads
are inside the if loop at the same time. It will destroy the singleton pattern and
both threads will get the different instanes of singleton lass. In ne4t setion,
we will see different ways to reate a thread1safe singleton lass.
Example Program #:
public class 7a5yInitiali5edSingleton2 :
private String name9
private double weight9
private float length9
private static 7a5yInitiali5edSingleton2 instance9
private 7a5yInitiali5edSingleton2)String name, double weight, float length* :
this.name ; name9
this.weight ; weight9
this.length ; length9
>
public static 7a5yInitiali5edSingleton2 getInstane)* :
if )instance ;; null* :
instance ; ne 7a5yInitiali5edSingleton2)#,iger#, E<.D<, D.Df*9
>
return instance9
>
?%'erride
public String toString)* :
return #7a5yInitiali5edSingleton2 @name;# A name A #, weight;# A weight
A #, length;# A length A #B#9
>
>
class Cgr. :
public static void main)String@B args* :
7a5yInitiali5edSingleton2 instane2 ;
7a5yInitiali5edSingleton2.getInstance)*9
7a5yInitiali5edSingleton2 instane3 ;
7a5yInitiali5edSingleton2.getInstance)*9
System.out.println)#instane2 0 # A instane2*9
System.out.println)#instane3 0 # A instane3*9
System.out.println) #instane2 ;; instane3 0 #
A )instane2 ;; instane3**9
>
>
!utput:
instane2 0 7a5yInitiali5edSingleton2 @name;,iger, weight;E<.D, length;D.DB
instane3 0 7a5yInitiali5edSingleton2 @name;,iger, weight;E<.D, length;D.DB
instane2 ;; instane3 0 true
5
&.'hread Safe Singleton:
,he easier way to reate a thread1safe singleton lass is to ma/e the global
aess method synhroni5ed, so that only one thread an e4eute this method at a
time.
Example Program &:
package singleton(
public class ,hreadSafeSingleton2 :
private String name9
private double weight9
private float length9
private static ,hreadSafeSingleton2 instance9
private ,hreadSafeSingleton2)String name, double weight, float length* :
this.name ; name9
this.weight ; weight9
this.length ; length9
>
public static synchronized ,hreadSafeSingleton2 getInstane)* :
if)instance ;; null* :
instance ; ne ,hreadSafeSingleton2)#7ion#, F<.G, D.Ff*9
>
return instance9
>
?%'erride
public String toString)* :
return #,hreadSafeSingleton2 @name;# A name A #, weight;# A weight
A #, length;# A length A #B#9
>
>
class CgrH :
public static void main)String@B args* :
,hreadSafeSingleton2 ob!2 ; ,hreadSafeSingleton2.getInstance)*9
,hreadSafeSingleton2 ob!3 ; ,hreadSafeSingleton2.getInstance)*9
System.out.println)#ob!2 0 # A ob!2*9
System.out.println)#ob!3 0 # A ob!3*9
System.out.println)#ob!2 ;; ob!3 0 # A )ob!2 ;; ob!3**9
>
>
!utput:
instane2 0 7a5yInitiali5edSingleton2 @name;,iger, weight;E<.D, length;D.DB
instane3 0 7a5yInitiali5edSingleton2 @name;,iger, weight;E<.D, length;D.DB
instane2 ;; instane3 0 true
6
Abo'e implementation wor/s fine and pro'ides thread1safety but it redues the
performane beause of ost assoiated with the synhroni5ed method, although we
need it only for the first few threads who might reate the separate instanes .
,o a'oid this e4tra o'erhead e'ery time, double checked locking priniple is used.
In this approah, the synhroni5ed blo/ is used inside the if ondition with an
additional he/ to ensure that only one instane of singleton lass is reated.
)elo code snippet provides the double checked locking implementation.
Example Program *:
public static synchronized 'hreadSafeSingleton" get%nstance+, -
if)instance ;; null* :
synchronized ),hreadSafeSingleton2.class* :
instance ; ne ,hreadSafeSingleton3)#7ion#, F<.G, D.Ff*9
>
>
return instance9
>
7
".Doubleton Design Pattern:
For any java class if we are allowed to create at-most two objects, such type of class is called as Doubleton
class8.
Example Program .:
public class $oubleton2 :
private static final $oubleton2 instances@B ; ne $oubleton2@3B9
private static int index9
private String name9
private double weight9
private float length9
static :
instances@<B ; ne $oubleton2)#,iger#, FD, D.Df*9
instances@2B ; ne $oubleton2)#7ion#, ID, D.3f*9
>
private $oubleton2)String name, double weight, float length* :
this.name ; name9
this.weight ; weight9
this.length ; length9
>
public static $oubleton2 getInstane)* :
return instances@)indexAA*J3B9
>
?%'erride
public String toString)* :
return #$oubleton2 @name;# A name A #, weight;# A weight
A #, length;# A length A #B#9
>
>
8
class CgrG :
public static void main)String@B args* :
$oubleton2 ob!2 ; $oubleton2.getInstance)*9
$oubleton2 ob!3 ; $oubleton2.getInstance)*9
$oubleton2 ob!. ; $oubleton2.getInstance)*9
$oubleton2 ob!H ; $oubleton2.getInstance)*9
$oubleton2 ob!D ; $oubleton2.getInstance)*9
$oubleton2 ob!G ; $oubleton2.getInstance)*9
System.out.println)#Printing the hashodes to he/ memory addresses#*9
System.out.println)#ob!2.hash-ode)* 0 # A ob!2.hash-ode)**9
System.out.println)#ob!..hash-ode)* 0 # A ob!..hash-ode)**9
System.out.println)#ob!D.hash-ode)* 0 # A ob!D.hash-ode)**9
System.out.println)#ob!3.hash-ode)* 0 # A ob!3.hash-ode)**9
System.out.println)#ob!H.hash-ode)* 0 # A ob!H.hash-ode)**9
System.out.println)#ob!G.hash-ode)* 0 # A ob!G.hash-ode)**9
System.out.println)#Printing the %b!et's Attributes#*9
System.out.println)#ob!2 0 # A ob!2*9
System.out.println)#ob!3 0 # A ob!3*9
System.out.println)#ob!. 0 # A ob!.*9
System.out.println)#ob!H 0 # A ob!H*9
System.out.println)#ob!D 0 # A ob!D*9
System.out.println)#ob!G 0 # A ob!G*9
>
>
!utput:
Printing the hashcodes to check memory addresses
ob!2.hash-ode)* 0 2GE2E22
ob!..hash-ode)* 0 2GE2E22
ob!D.hash-ode)* 0 2GE2E22
ob!3.hash-ode)* 0 22.FH<..
ob!H.hash-ode)* 0 22.FH<..
ob!G.hash-ode)* 0 22.FH<..
Printing the !b/ect0s 1ttributes
ob!2 0 $oubleton2 @name;,iger, weight;FD.<, length;D.DB
ob!3 0 $oubleton2 @name;7ion, weight;ID.<, length;D.3B
ob!. 0 $oubleton2 @name;,iger, weight;FD.<, length;D.DB
ob!H 0 $oubleton2 @name;7ion, weight;ID.<, length;D.3B
ob!D 0 $oubleton2 @name;,iger, weight;FD.<, length;D.DB
ob!G 0 $oubleton2 @name;7ion, weight;ID.<, length;D.3B
9
Example Program 2:
package doubleton(
public class $oubleton3 :
private static $oubleton3 instane29
private static $oubleton3 instane39
private String name9
private double weight9
private float length9
private $oubleton3)String name, double weight, float length* :
this.name ; name9
this.weight ; weight9
this.length ; length9
>
public static $oubleton3 getInstane)* :
if)instane2 ;; null* :
instane2 ; ne $oubleton3)#-heetah#, 23<, D.Df*9
return instane29
>
else if )instane3 ;; null* :
instane3 ; ne $oubleton3)#6lephant#, .<<, E.3f*9
return instane39
>
else :
if )Cath.random)* K<.D* :
return instane29
>
else :
return instane39
>
>
>
?%'erride
public String toString)* :
return #$oubleton3 @name;# A name A #, weight;# A weight
A #, length;# A length A #B#9
>
>
10
class CgrE :
public static void main)String@B args* :
$oubleton3 ob!2 ; $oubleton3.getInstane)*9
$oubleton3 ob!3 ; $oubleton3.getInstane)*9
$oubleton3 ob!. ; $oubleton3.getInstane)*9
$oubleton3 ob!H ; $oubleton3.getInstane)*9
$oubleton3 ob!D ; $oubleton3.getInstane)*9
$oubleton3 ob!G ; $oubleton3.getInstane)*9
System.out.println)#Printing the hashodes to he/ memory addresses#*9
System.out.println)#ob!2.hash-ode)* 0 # A ob!2.hash-ode)**9
System.out.println)#ob!..hash-ode)* 0 # A ob!..hash-ode)**9
System.out.println)#ob!D.hash-ode)* 0 # A ob!D.hash-ode)**9
System.out.println)#ob!3.hash-ode)* 0 # A ob!3.hash-ode)**9
System.out.println)#ob!H.hash-ode)* 0 # A ob!H.hash-ode)**9
System.out.println)#ob!G.hash-ode)* 0 # A ob!G.hash-ode)**9
System.out.println)#Printing the %b!et's Attributes#*9
System.out.println)#ob!2 0 # A ob!2*9
System.out.println)#ob!3 0 # A ob!3*9
System.out.println)#ob!. 0 # A ob!.*9
System.out.println)#ob!H 0 # A ob!H*9
System.out.println)#ob!D 0 # A ob!D*9
System.out.println)#ob!G 0 # A ob!G*9
>
>
!utput:
Printing the hashcodes to check memory addresses
ob!2.hash-ode)* 0 H.IHEF<
ob!..hash-ode)* 0 FG.HFF.
ob!D.hash-ode)* 0 FG.HFF.
ob!3.hash-ode)* 0 FG.HFF.
ob!H.hash-ode)* 0 H.IHEF<
ob!G.hash-ode)* 0 FG.HFF.
Printing the !b/ect0s 1ttributes
ob!2 0 $oubleton3 @name;-heetah, weight;23<.<, length;D.DB
ob!3 0 $oubleton3 @name;6lephant, weight;.<<.<, length;E.3B
ob!. 0 $oubleton3 @name;6lephant, weight;.<<.<, length;E.3B
ob!H 0 $oubleton3 @name;-heetah, weight;23<.<, length;D.DB
ob!D 0 $oubleton3 @name;6lephant, weight;.<<.<, length;E.3B
ob!G 0 $oubleton3 @name;6lephant, weight;.<<.<, length;E.3B
11
#.%mmutable Design Pattern:
%mmutable ob/ects are instanes whose state doesn8t hange after it has been
initiali5ed.
For e4ample, String is an immutable lass and one instantiated its 'alue ne'er
hanges.
Immutable ob!ets are good for ahing purpose beause you don8t need to worry
about the 'alue hanges. %ther benefit of immutable lass is that it is inherently
thread3safe, so you don8t need to worry about thread safety in ase of multi1
threaded en'ironment.
,o reate a lass immutable, follow following steps0
2.$elare the lass as final so it an8t be e4tended.
3.Ca/e all fields pri'ate so that diret aess is not allowed.
..$on8t pro'ide setter methods for 'ariables
4.Ca/e all mutable fields final so that it8s 'alue an be assigned only one.
D.Initiali5e all the fields 'ia a onstrutor performing deep opy.
G.Perform loning of ob!ets in the getter methods to return a opy rather
than returning the atual ob!et referene.
,o understand points H and D, let8s run the sample Final lass that wor/s well and
'alues doesn8t get altered after instantiation.
12
Example Program 4:
package immutable(
final class Immutable-lass2 :
private final int id9
private final String name9
public Immutable-lass2)int id, String name* :
this.id ; id9
this.name ; name9
>
public int getId)* :
return id9
>
public String getName)* :
return name9
>
?%'erride
public String toString)* :
return #Immutable-lass2 @id;# A id A #, name;# A name A #B#9
>
>
class CgrI :
public static void main)String@B args* :
Immutable-lass2 ob!2 ; ne Immutable-lass2)2<, #Sashi#*9
Immutable-lass2 ob!3 ; ne Immutable-lass2)3<, #(eerthana#*9
System.out.println)#ob!2 0 # A ob!2*9
System.out.println)#ob!3 0 # A ob!3*9
>
>
!utput:
ob!2 0 Immutable-lass2 @id;2<, name;SashiB
ob!3 0 Immutable-lass2 @id;3<, name;(eerthanaB
Lere ob!et got initiali5ed in ontrutor, No setter methods are there to modify
%b!et's State.
%b!et's attributes delared with final, so ob!et's attributes annot be modified
again.
%b!et's attributes delared with pri'ate, so that diret aess is not allowed.
Lere anyone an get the partiular ob!et's attribute by using getter Cethods, but
they annot set its 'alue.
13

You might also like