The Singleton pattern is a creational design pattern that restricts the instantiation of a class to one instance and provides a global point of access to that instance.
Here's an example of how to implement the Singleton pattern in C#:
main.cs468 chars25 lines
In this implementation, the Singleton class is marked as sealed
to prevent inheritance. The class has a private static variable instance
which stores the single instance of the class. The padlock
object is used to synchronize threads and avoid race conditions.
The class has a private constructor to prevent direct instantiation from outside the class. The only way to obtain the single instance is through the Instance
property, which returns the instance
variable after creating it if it hasn't been created already.
This implementation provides a thread-safe way of creating a single instance of the Singleton class, without the need for locks on every access to Instance
.
gistlibby LogSnag