vimwiki/tech/singleton.wiki

24 lines
784 B
Plaintext

= Singleton =
A singleton is a design pattern in which a class has only one instance, and
that instance is globally accessable. This is often important for use in shared
resources, such as a file, database connection, or logging application.
== Implementation ==
* Make the default constructor private, preventing other objects from using
`new`
* Create a static creation method that acts as a constructor. This method calls
a private constructor and instantiates a static field, which is the
singleton. All further calls return a reference to this cached, static
object.
== Use case ==
* strict control over global vars
* instance where a single instance of an object is required
== Cons ==
* Take special care to not instantiate several in a multithreaded enviroment