Anda di halaman 1dari 9

Penerapan Singleton Pattern yang Efektif

Jadi, ada penerapan singleton yang lebih efektif daripada 4 langkah ini:
1. Buat konstruktor private
2. Buat method static untuk mengambil objek
. !plikasikan synchroni"e terhadap method tersebut
4. #verride method clone yang melempar error.
$ara2 di atas, itu old%fashioned& !da cara efektifnya... '( nemunya karena g( gak ngerti yang nomor
4. Buat nge%override method clone, kan harus implements interface $loneable. )mang itu penting*&
Belum lagi sifatnya jugak protected... bukan public.
'( nemu ja(abannya di sini: http:++stackoverflo(.com+,uestions+-1./0+singleton%design%pattern%
and%preventing%cloning. 1ertanyaan yang sama ama pertanyaan g(, dan akhirnya dija(ab kalo
ngeimplementasiin singleton tuh pake caranya Joshua Bloch di bukunya 2)ffective Java3.
4engkapnya gini:
public class Singleton
{
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private Singleton() {}
private static fnal class SingletonHolder {
static fnal Singleton instance = new Singleton();
}
}

5api cara di atas masih sama ajah old%fashioned nya. $ara terbaru pake single%element enum. $aranya:
// Enu singleton ! t"e pre#erred approac"
public enu Elvis {
I$S%&$'E;
public void leave%"e(uilding() { ... }
}
'itu... trus lebihnya yaaa sama ajah.
6alo penasaran, lengkapnya gini:
public enum 5unggal 7
89:5!9$);
private int <;
public int get=>? 7
return <;
@
public void set=>int <? 7
this.< A <;
@
public void method!>?7
:ystem.out.println>BCaiiiiB?;
@
@
public class Dain 7
public static void main>:tringEF args? 7
++bentuk objek
5unggal.89:5!9$).method!>?;
5unggal.89:5!9$).set=>/?;
:ystem.out.println>BCarga <: BG5unggal.89:5!9$).get=>??;
@
@
Kalo mau tau lebih lengkap tentang enum, ini ada artikel gw ambil dari
http://javarevisited.blogspot.com/2011/08/enuminjavae!ampletutorial.html sama
http://docs.oracle.com/javase/tutorial/java/java""/enum.html
#ara ngegunain enum:
public enum $a% &
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class 'num(est &
Day day;

public EnumTe!"Day day# $
!%i&day ' day;
}

public ()id !ellI!*i+eI!I"# $
,i!c% "day# $
cae MONDAY-
Sy!em&)u!&p.in!ln"/M)nday a.e bad&/#;
b.ea+;

cae FRIDAY-
Sy!em&)u!&p.in!ln"/F.iday a.e be!!e.&/#;
b.ea+;

cae SATURDAY- cae SUNDAY-
Sy!em&)u!&p.in!ln"/Wee+end a.e be!&/#;
b.ea+;

de0aul!-
Sy!em&)u!&p.in!ln"/Mid,ee+ day a.e )1)&/#;
b.ea+;
}
}

public !a!ic ()id main"S!.in234 a.2# $
EnumTe! 0i.!Day ' ne, EnumTe!"Day&MONDAY#;
0i.!Day&!ellI!*i+eI!I"#;
EnumTe! !%i.dDay ' ne, EnumTe!"Day&WEDNESDAY#;
!%i.dDay&!ellI!*i+eI!I"#;
EnumTe! 0i0!%Day ' ne, EnumTe!"Day&FRIDAY#;
0i0!%Day&!ellI!*i+eI!I"#;
EnumTe! i5!%Day ' ne, EnumTe!"Day&SATURDAY#;
i5!%Day&!ellI!*i+eI!I"#;
EnumTe! e(en!%Day ' ne, EnumTe!"Day&SUNDAY#;
e(en!%Day&!ellI!*i+eI!I"#;
}
}
(erus artikel terkait:
What is Enum in Java
Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java,
For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in
Java was introduced in J! ".# and it is one of my favorite features of J$SE # amon% &utoboxin% and
unboxin% , 'enerics, varar%s and static import. (ne of the common use of Enum which emer%ed in recent
years is )sing 'num to write *ingleton in +ava, which is by far easiest way to implement Sin%leton and
handles several issues related to thread)safety and Seriali*ation automatically. +y the way, Java Enum as
type is more suitable to represent well known fixed set of thin%s and state, for example representin% state of
(rder as NEW, ,&-./&0 F/00, F/00 or 10(SE. Enumeration2Enum3 was not ori%inally available in Java
thou%h it was available in other lan%ua%e like 1 and 144 but eventually Java reali*ed and introduced Enum
on J! # 2.i%er3 by keyword Enum. /n this Java Enum tutorial we will see different Enum example in
Java and learn usin% Enum in Java. Focus of this Java Enum tutorial will be on different features provided by
Enum in Java and how to use them. /f you have used Enumeration before in 1 or 144 than you will not be
uncomfortable with Java Enum but in my opinion Enum in Java is more rich and versatile than in any other
lan%ua%e. . +y the way, if you like to learn new concepts usin% book than you can also see Java #.5 .i%er 6 &
evelopers notebook, / had followed this book while learnin% Enum, when Java ".# was first launched. .his
book has excellent chapter not only on Enum but also on key features of Java ".# and worth readin%.
How to represent enumerable value without Java enum
Since Enum in Java is only available from Java 1.5 its worth to discuss how we used to
represent enumerable values in Java prior J! ".# and without it. / use public static final constant to
replicate enum like behavior. 0et7s see an Enum example in Java to understand the concept better. /n this
example we will use 8S 1urrency 1oin as enumerable which has values like ,ENN9 2"3 N/1!0E 2#3, /:E
2"53, and ;8&-.E- 2$#3.
public class CurrencyDenom {
public static final int PENNY = 1;
public static final int NICKLE = 5;
public static final int DIME = 10;
public static final int QUARTER = 25;
}
public class Currency {
private int currency; //CurrencyDenom.PENN!CurrencyDenom.N"C#$E!
// CurrencyDenom.D"%E!CurrencyDenom.&'()*E)
}
.hou%h this can server our purpose it has some serious limitations6
1) No Type-Saety6 First of all it7s not type%safe< you can assi%n any valid int value to currency e.%. ==
thou%h there is no coin to represent that value.
!) No "eanin#ul $rintin#6 printin% value of any of these constant will print its numeric value instead of
meanin%ful name of coin e.%. when you print N/1!0E it will print >#> instead of >N/1!0E>
%) No namespa&e' to access the currencyDenom constant we need to prefix class name e.%.
CurrencyDenom.PENN instead of ?ust usin% ,ENN9 thou%h this can also be achieved by usin% static import
in JH6 1./
Java Enum is answer of all this limitation. Enum in Java is type)safe, provides meanin%ful Strin% names and
has there own namespace. Now let@s see same example usin% Enum in Java6
public enum Currency {PENN! N"C#$E! D"%E! &'()*E)};

Aere 1urrency is our enum and PENN! N"C#$E! D"%E! &'()*E) are enum &onstants. Notice &urly
(ra&es around enum &onstants because Enum are type like class and interface in Java. &lso we have
followed similar namin% convention for enum like class and interface 2first letter in 1aps3 and since Enum
constants are implicitly static final we have used all caps to specify them like 1onstants in Java.
What is Enum in Java
Now back to primary Buestions CWhat is Enum in )ava* simple answer Enum is a keyword in java and on
more detail term Java Enum is type like class and interface and can be used to define a set of Enum
constants. Enum constants are implicitly static and final and you can not chan%e there value once created.
Enum in Java provides type)safety and can be used inside switch statment like int variables. Since enum is a
keyword you can not use as variable name and since its only introduced in J! ".# all your previous code
which has enum as variable name will not work and needs to be re)factored.
Benefits of Enums in Java:
"3 Enum is type-sae you can not assi%n anythin% else other than predefined Enum constants to an Enum
variable. /t is compiler error to assi%n somethin% else unlike the public static final variables used in Enum int
pattern and Enum Strin% pattern.
$3 Enum has its own name)space.
D3 +est feature of Enum is you &an use Enum in Java inside Swit&h statement like int or char primitive
data type.we will also see example of usin% ?ava enum in switch statement in this ?ava enum tutorial.
E3 &ddin% new constants on Enum in Java is easy and you can add new constants without breakin% existin%
code.
Important points about Enum in Java
"3 Enums in Java are type-sae and has there own name)space. /t means your enum will have a type for
example >1urrency> in below example and you can not assi%n any value other than specified in Enum
1onstants.

public enum Currency {PENNY! NICKLE! DIME! QUARTER};
Currency coin = Currency.PENN;
coin = 1; //compilation error
$) Enum in Java are reeren&e type like class or interface and you can define constructor, methods and
variables inside ?ava Enum which makes it more powerful than Enum in 1 and 144 as shown in next
example of Java Enum type.
D3 9ou can spe&iy values o enum &onstants at the &reation time as shown in below example6
public enum Currency {PENNY+1,! NICKLE+5,! DIME+10,! QUARTER+25,};
+ut for this to work you need to define a member variable and a constructor because ,ENN9 2"3 is actually
calling a constructor which accepts int value , see below example.

public enum Currency {
PENNY+1,! NICKLE+5,! DIME+10,! QUARTER+25,;
private int -alue;
private Currency+int -alue, {
this.-alue = -alue;
}
};
+onstru&tor o enum in )ava must be private any other access modifier will result in compilation error.
Now to %et the value associated with each coin you can define a public .et/alue+, method inside ?ava
enum like any normal ?ava class. &lso semi colon in the first line is optional.
E3 Enum constants are implicitly static and final and can not be chan%ed once created. For example below
code of ?ava enum will result in compilation error6
Currency.PENN = Currency.D"%E;
.he final field EnumE0amples.Currency.PENN cannot be re assi%ned.


#3 Enum in )ava &an (e used as an ar#ument on swit&h statment and with >case6> like int or char
primitive type. .his feature of ?ava enum makes them very useful for switch operations. 0et7s see an example
of how to use ?ava enum inside switch statement6
Currency usCoin = Currency.D"%E;
switch +usCoin, {
case PENN1
2ystem.out.println+3Penny coin3,;
break;
case N"C#$E1
2ystem.out.println+3Nic4le coin3,;
break;
case D"%E1
2ystem.out.println+3Dime coin3,;
break;
case &'()*E)1
2ystem.out.println+3&uarter coin3,;
}

from JH6 I on(ards you can also :tring in :(itch case in Java code.
F3 Since &onstants deined inside Enum in Java are inal you &an saely &ompare them usin# ,--,
e.uality operator as shown in followin% example of Java Enum6
Currency usCoin = Currency.D"%E;
if+usCoin == Currency.D"%E,{
2ystem.out.println+3enum in 5a-a can be compare6 usin. ==3,;
}
By the (ay comparing objects using AA operator is not recommended, !l(ays use e,uals>? method or
compare5o>? method to compare #bjects.
G3 Java compiler automatically %enerates static -alues+, method for every enum in ?ava. /alues+, met7o6
returns array of Enum constants in the same order they have listed in Enum and you can use -alues+, to
iterate over values of Enum in Java as shown in below example6
for+Currency coin1 Currency.-alues+,,{
2ystem.out.println+3coin1 3 8 coin,;
}
&nd it will print6
coin: PENNY
coin: NICKLE
coin: DIE
coin: !"#$%E$

Notice the order its exactly same with deined order in enums.

H3 /n Java Enum can override methods also. 0et7s see an example of overridin% to2trin.+, method inside
Enum in Java to provide meanin#ul des&ription for enums constants.
public enum Currency {
........

9:-erri6e
public 2trin. to2trin.+, {
switch +this, {
case PENN1
2ystem.out.println+3Penny1 3 8 -alue,;
break;
case N"C#$E1
2ystem.out.println+3Nic4le1 3 8 -alue,;
break;
case D"%E1
2ystem.out.println+3Dime1 3 8 -alue,;
break;
case &'()*E)1
2ystem.out.println+3&uarter1 3 8 -alue,;
}
return super.to2trin.+,;
}
};
&nd here is how it looks like when displayed6
Currency usCoin = Currency.DIME;
2ystem.out.println+usCoin,;
output:
Dime: &'

=3 .wo new collection classes Enumap and Enum(et are added into collection packa%e to support Java
Enum. .hese classes are hi%h performance implementation of Dap and :et interface in Java and we should
use this whenever there is any opportunity.
"5) /ou &an not &reate instan&e o enums (y usin# new operator in Java because constructor of Enum
in Java can only be private and Enums constants can only be created inside Enums itself.
""3 /nstance of Enum in Java is created when any Enum constants are first called or referenced in code.
"$3 Enum in Java &an implement the intera&e and override any method like normal class /t7s also worth
notin% that Enum in ?ava implicitly implement both :eriali"able and $omparable interface. 0et@s see and
example of how to implement intera&e usin# Java Enum6
public enum Currency implements )unnable{
PENN+1,! N"C#$E+5,! D"%E+10,! &'()*E)+25,;
private int -alue;
............

9:-erri6e
public voi) run+, {
2ystem.out.println+3Enum in ;a-a implement inter<aces3,;

}
}
"D3 /ou &an deine a(stra&t methods inside Enum in Java and can also provide different
implementation for different instances of enum in ?ava. 0et7s see an example of using abstract method
inside enum in java
public enum Currency implements )unnable{
PENN+1, {
9:-erri6e
public 2trin. color+, {
return 3copper3;
}
}! N"C#$E+5, {
9:-erri6e
public 2trin. color+, {
return 3bron=e3;
}
}! D"%E+10, {
9:-erri6e
public 2trin. color+, {
return 3sil-er3;
}
}! &'()*E)+25, {
9:-erri6e
public 2trin. color+, {
return 3sil-er3;
}
};
private int -alue;
public abstract 2trin. color+,;

private Currency+int -alue, {
this.-alue = -alue;
}
..............
}
/n this example since every coin will have different color we made the color+, method abstract and let each
instance of Enum to define there own color. 9ou can %et color of any coin by ?ust callin% color+, method as
shown in below example of ?ava enum6
2ystem.out.println+3Color1 3 8 Currency.D"%E.color+,,;

Enum Java value0 e1ample
(ne of my reader pointed out that / have not mention about value(f method of enum in Java, which is used
to convert Strin% to enum in ?ava. Aere is what he has su%%ested, thanks I &nonymous
29ou could also include value0() method o enum in ?ava which is added by compiler in any enum alon%
with values23 method. Enum value0() is a static method which takes a strin% ar%ument and can be used to
convert a Strin% into enum. (ne think thou%h you would like to keep in mind is that value(f2Strin%3 method
of enum will throw >E1&eption in thread ,main, )ava.lan#.2lle#al3r#umentE1&eption' No enum &onst
&lass> if you supply any strin% other than enum values.
&nother of my reader su%%ested about or6inal+, and name+, utility method of ?ava enum (rdinal method of
Java Enum returns position of a Enum constant as they declared in enum while name23of Enum returns the
exact strin% which is used to create that particular Enum constant.J name23 method can also be used for
convertin% Enum to Strin% in Java.
.hat7s all on Java enum , ,lease share if you have any nice tips on enum in Java and let us know how you
are usin% ?ava enum in your work. 9ou can also follow some %ood advice for usin% Enum by Joshua +loch in
his all time classic book Effective Java. .hose advice will %ive you more idea of usin% this powerful feature of
Java pro%rammin% lan%ua%e
Jead more: http:++javarevisited.blogspot.com+2.11+.0+enum%in%java%e<ample%
tutorial.htmlKi<""2(hrkc(bB

Anda mungkin juga menyukai