Definition
The singleton is a class that has only one instance and provides a global point of access to it.
Concept
A particular class should have only one instance. You can use this instance whenever you need it and therefore avoid creating unnecessary objects.
Real-Life Example
Suppose you are a member of a sports team and your team is participating in a tournament. When your team plays against another team, as per the rules of the game, the captains of the two sides must have a coin toss. If your team does not have a captain, you need to elect someone to be the captain first. Your team must have one and only one captain.
Computer World Example
In some software systems, you may decide to maintain only one file system so that you can use it for the centralized management of resources.
Example
- using System;
- namespace SingletonPatternEx {
- public sealed class Singleton {
- private static readonly Singleton instance = new Singleton();
- private int numberOfInstances = 0;
-
-
- private Singleton() {
- Console.WriteLine("Instantiating inside the private constructor.");
- numberOfInstances++;
- Console.WriteLine("Number of instances ={0}", numberOfInstances);
- }
- public static Singleton Instance {
- get {
- Console.WriteLine("We already have an instance now.Use it.");
- Chapter 1 Singleton Pattern
- 9
- return instance;
- }
- }
- }
- class Program {
- static void Main(string[] args) {
- Console.WriteLine("***Singleton Pattern Demo***\n");
-
-
- Console.WriteLine("Trying to create instance s1.");
- Singleton s1 = Singleton.Instance;
- Console.WriteLine("Trying to create instance s2.");
- Singleton s2 = Singleton.Instance;
- if (s1 == s2) {
- Console.WriteLine("Only one instance exists.");
- } else {
- Console.WriteLine("Different instances exist.");
- }
- Console.Read();
- }
- }
- }