It is sometimes the case that there must really only be one instance of some particular class in a system. For example, a class which provides access to some data that everything else in the application uses. This is a common situation for which there is a standard OO design pattern. In Java it can be implemented like this:
public class OneOff implements java.io.Serializable
{
private static final OneOff INSTANCE = new OneOff ();
/** Do not allow overriding: final */
public static final OneOff getInstance ()
{
return INSTANCE;
}
private OneOff () { ... } // Constructor must be made private. So cannot sub-class
/** Ensures deserialisation gives same object (NB: RMI) */
private Object readResolve () throws java.io.ObjectStreamException
{
return INSTANCE;
}
// ... etc: instance fields and methods
} // OneOff
Client class for this cannot use new
, only call OneOff.getInstance ()
A common alternate is to construct the one object when getInstance () is first called, but then that method must be synchronized. Above is from a Sun "Tech Tip".