स्थिर चर के भार के साथ एक स्थिर वर्ग एक हैक का एक सा है।
/**
* Grotty static semaphore
**/
public static class Ugly {
private static int count;
public synchronized static void increment(){
count++;
}
public synchronized static void decrement(){
count--;
if( count<0 ) {
count=0;
}
}
public synchronized static boolean isClear(){
return count==0;
}
}
वास्तविक उदाहरण के साथ एक सिंगलटन बेहतर है।
/**
* Grotty static semaphore
**/
public static class LessUgly {
private static LessUgly instance;
private int count;
private LessUgly(){
}
public static synchronized getInstance(){
if( instance==null){
instance = new LessUgly();
}
return instance;
}
public synchronized void increment(){
count++;
}
public synchronized void decrement(){
count--;
if( count<0 ) {
count=0;
}
}
public synchronized boolean isClear(){
return count==0;
}
}
राज्य केवल उदाहरण में है।
तो सिंगलटन को बाद में पूलिंग, थ्रेड-लोकल इंस्टेंस आदि के लिए संशोधित किया जा सकता है और लाभ पाने के लिए पहले से लिखे कोड में से किसी को बदलने की जरूरत नहीं है।
public static class LessUgly {
private static Hashtable<String,LessUgly> session;
private static FIFO<LessUgly> freePool = new FIFO<LessUgly>();
private static final POOL_SIZE=5;
private int count;
private LessUgly(){
}
public static synchronized getInstance(){
if( session==null){
session = new Hashtable<String,LessUgly>(POOL_SIZE);
for( int i=0; i < POOL_SIZE; i++){
LessUgly instance = new LessUgly();
freePool.add( instance)
}
}
LessUgly instance = session.get( Session.getSessionID());
if( instance == null){
instance = freePool.read();
}
if( instance==null){
// TODO search sessions for expired ones. Return spares to the freePool.
//FIXME took too long to write example in blog editor.
}
return instance;
}
एक स्थिर वर्ग के साथ कुछ ऐसा ही करना संभव है लेकिन अप्रत्यक्ष प्रेषण में प्रति कॉल ओवरहेड होगा।
आप उदाहरण प्राप्त कर सकते हैं और इसे एक तर्क के रूप में फ़ंक्शन में पास कर सकते हैं। इससे कोड को "सही" सिंगलटन पर निर्देशित किया जा सकता है। हम जानते हैं कि आपको केवल इसकी आवश्यकता होगी ... जब तक आप नहीं करते।
बड़ा लाभ यह है कि स्टेटफुल सिंग्लेट्स को थ्रेड सुरक्षित बनाया जा सकता है, जबकि एक स्थिर वर्ग नहीं कर सकता, जब तक कि आप इसे एक गुप्त सिंगलटन संशोधित न करें।