From the course: Java Design Patterns: Creational
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Implement the Singleton pattern - Java Tutorial
From the course: Java Design Patterns: Creational
Implement the Singleton pattern
- [Instructor] Here is a public class called PrintSpooler that implements the singleton pattern. The PrintSpooler class has a private static field called spooler, which is of type, PrintSpooler. This is the one and only instance of the PrintSpooler class. There is another private static field which is called initialized. This is a Boolean flag to mark if the object has been initialized. Before the first PrintSpooler object is created, this flag is set to False. The most important part of the PrintSpooler class is the private constructor. Having a private constructor prevents code from any other class creating new PrintSpooler objects. The only place to create PrintSpooler objects is from within the PrintSpooler class itself. This way, the constructor is only called once. In this example, that happened when the instance variable is initialized. Note that initialization of the object is also separated out in a private method called init. In this example, the method is empty to keep the…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.