Making Global Objects

Making Global Objects

Let’s take an example: a program has a PrintSpooler class. This class maintains a queue for printer requests and serializes them. The program cannot contain multiple PrintSpooler Objects because this can create unexpected printer output, thus defeating the purpose of having a Spooler class. Global variables are not permitted in Java, but in these types of situations they are needed. A way around this is to use the same object throughout the program. Code can be classed in such a way that it affords the facility of using it like a global object. The following code shows how to do this:

 class PrintSpooler {	static PrintSpooler pr;	private PrintSpooler(){}; //Don't let anyone create objects directly	public static PrintSpooler get() //Provide access to the shared PrintSpooler object	{		if(pr == null)			pr = new PrintSpooler();		return pr;	}		public void print(String str){/*Print the string*/};	//Other member functions}

Making the constructor private disallows direct object creation. Static function


Share the Post: