In this video, learn how a class uses the Singleton pattern to ensure that only one instance of it can be created. Learn how to create a Singleton class by using a private constructor.
- [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 example simple,…but in a more complex program,…
Released
8/29/2018- What are creational design patterns?
- Avoid complex constructors
- Implementing the Builder pattern
- Multithreading with the Singleton pattern
- Using the Prototype pattern
- Implementing a simple Factory Method pattern
- Making code more flexible with the Abstract Factory pattern
Share this video
Embed this video
Video: Implement the Singleton pattern