• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Singleton implementation Not possible?

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following implementation of Singleton Pattern.


class SingletonException extends RuntimeException
{
//new exception type for singleton classes
public SingletonException()
{
super();
}
//-----------------------------------------------
public SingletonException(String s)
{
super(s);
}
}

class PrintSpooler
{
//this is a prototype for a printer-spooler class
//such that only one instance can ever exist
static boolean
instance_flag=false; //true if 1 instance
public PrintSpooler() throws SingletonException
{
if (instance_flag)
throw new SingletonException("Only one spooler allowed");
else
instance_flag = true; //set flag for 1 instance
System.out.println("spooler opened");
}
//-------------------------------------------
public void finalize()
{
instance_flag = false; //clear if destroyed
}
}

//-----------------------------------------------------------------------



Here we are using finalize method to reset the instance_flag variable so that we are able to create a instance if no instance is in Existance.

My question is
Since we cannot rely on finally method to be executed everytime
how do we make sure that the instance_flag is reset ?
is it possible to implement Singleton pattern without any ambiquity?

Thanks,
Pramod.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry Pramod, but this is not a SCJP issue. Moving it to ... OO, Patterns, whatever forum.
[ December 13, 2004: Message edited by: Barry Gaunt ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic