| by Arround The Web | No comments

Singleton Design Pattern in C#

The singleton design pattern is widely used in object-oriented programming as it ensures that only one class instance is created, and to access it provides a global point of access. This means that every request for an instance of the class returns the same instance, rather than creating a new one.

Singleton Design Pattern in C#

The singleton pattern is known for its simplicity and effectiveness in ensuring that there is only one instance of the class, making it a popular choice for many software developers. The singleton pattern is often used to ensure that a single point of access exists to a shared resource or service, here is the syntax for using it:

public sealed class <ClassName>

{

   private static readonly <ClassName> instance = new <ClassName>();

   private <ClassName>() {}

   public static <ClassName> Instance

   {

      get

      {

            return instance;

      }

   }

}

The sealed keyword is used to prevent the class from being inherited and the instance field is marked as read-only to ensure that it can only be initialized once, and it is initialized at declaration with a single instance of the class. The constructor is marked as private to prevent external instantiation of the class and the Instance property provides a way to access the single instance of the class and is marked as static so that it can be accessed without creating an instance of the class.

In C# A singleton pattern is typically implemented using a private constructor, a static instance field, and a public static property or method to access the instance. The basic idea is to ensure that only one instance of the class can exist by controlling how it is instantiated and accessed, here is an example code that demonstrates the creation and use of the singleton design pattern in C#:

using System;

/*Define the Calculator class with a private constructor and a static instance field*/
public sealed class Calculator
{
    private static Calculator instance;

    private Calculator() { } /* Private constructor prevents instantiation of Calculator class from outside the class itself*/

    /*Define the Instance property, which creates a new Calculator object if one doesn't already exist and returns it*/
    public static Calculator Instance
    {
        get
        {
            if (instance == null) /* Check if a Calculator object has already been created*/
            {
                instance = new Calculator(); /* If not, create a new Calculator object and assign it to the instance field*/
            }
            return instance;         }
    }

        public int Add(int x, int y)
    {
        return x + y;
    }
    /* Define the Subtract method, which subtracts one integer from another and returns the result*/
    public int Subtract(int x, int y)
    {
        return x - y;
    }
}
// Define the Program class with a Main method
class Program
{
    static void Main(string[] args)
    {
        Calculator calc = Calculator.Instance; /* Get an instance of the Calculator object using the Instance property*/
        int result1 = calc.Add(5, 7); /* Use the Add method to add 5 and 7 together*/
        Console.WriteLine($"Result1: {result1}"); /* Output the result of the addition to the console*/

        int result2 = calc.Subtract(10, 3); /* Use the Subtract method to subtract 3 from 10*/
        Console.WriteLine($"Result2: {result2}"); /* Output the result of the subtraction to the console*/
    }
}

This example defines The Calculator class with a private constructor and a static instance field. The private constructor prevents the class from being instantiated from outside the class itself, while the static instance field ensures that only one instance of the class can exist at a time.

The Calculator class also includes an Instance property, which creates a new Calculator object if one doesn’t already exist and returns it. The first time the Instance property is called, it creates a new Calculator object and assigns it to the instance field, any subsequent calls to the Instance property simply return the existing Calculator object.

The Calculator class also includes Add and Subtract methods, which perform basic arithmetic operations and return the result. These methods are just included as an example of the kind of functionality that the Calculator class could provide.

Finally, the Program class includes a Main() method, which creates an instance of the Calculator class using the Instance property and uses the Add and Subtract methods to perform some simple calculations. The results of these calculations are then output to the console using the Console.WriteLine() method.

If we attempt to create a new instance of the Calculator class using the default constructor. This will not work because the constructor of the Calculator class is private, which prevents new instances from being created outside of the class.

To demonstrate I created a new instance of the Calculator class using the Instance property of the class and in the output, there will be an error that states this class is inaccessible due to its protection level:

By demonstrating that new instances are rejected by the singleton pattern in C#, this example shows how the singleton pattern ensures that only one class instance is created and maintained throughout the program.

Conclusion

The singleton pattern is often used in situations where a single object needs to coordinate actions across the system, such as a logging service or a database connection. The pattern is implemented using a private constructor and a static property that returns a single instance of the class, this article gives a detailed explanation about this pattern.

Share Button

Source: linuxhint.com

Leave a Reply