Monday 23 February 2009

Notes on Lecture 7 : Singleton Pattern

On the Singleton implementation shown below, there was a question on why the getSpooler() method does not seem to have a return value in the signature, although the singleton instance _spooler is returned at the end of the method implementation:

That was a typo and I have corrected it. The return type in the signature should be PrintSpooler.

There was also a question relating to declaring the constructor as "private" and whether we may have multiple constructors and whether they would all be private. We make the constructor private so an instance can only be created from within the static method of the class. Since we are only interested in having a single instance of PrintSpooler, it is rather unlikely that we would need the flexibility of having more than one constructors. Most likely we are able to define our one instance exactly and assign a single constructor to it. Certainly, the classic version of Singleton has one constructor. However, if we did have more than one constructor, they would all need to be declared "private" for the same reason.

Public class PrintSpooler {

// a prototype for a spooler class,

// such that only one instance can ever exist

private static PrintSpooler _spooler;

private PrintSpooler()

{ /* private constructor */ }

public static synchronized PrintSpooler

getSpooler() {

if (_spooler == null) _spooler = new

PrintSpooler();

return _spooler;

}

}

No comments: