From the course: Java Design Patterns: Creational

Unlock the full course today

Join today to access over 22,700 courses taught by industry experts or purchase this course individually.

Java's Collection class

Java's Collection class - Java Tutorial

From the course: Java Design Patterns: Creational

Start my 1-month free trial

Java's Collection class

- [Instructor] There are several examples of the singleton pattern from the Java API itself, and a similar effect is used with Java's Collections class. The Collections class itself is not an example of the singleton pattern, but the class comes with three methods that can be used to create singleton collections. These are singletonList, singletonMap, and singletonSet. These methods return an immutable collection. SingletonList returns a list, singletonMap returns a map, and singletonSet returns a set. They all return collections that contain only one object, and no new objects can be added to them. Using these methods does not turn the collection into a singleton, because it does not stop you creating new collections, but like a singleton, it does provide a single point of access that always returns the same instance. In this example, there is a class called PrintSpooler that manages access to printers. In this example, it is empty, but in a real application, it would contain codes…

Contents