Thursday, April 25, 2024
HomeC#Implementing Singleton Sample In C#

Implementing Singleton Sample In C#


Singleton is a creational design sample. I believe even a junior developer ought to know at the least this design sample. It’s probably the most used design sample and is easy.

This sample solves the issue if you need to have just one occasion. For instance, let’s take into consideration a connection to a server. You don’t need to open a number of connections from the identical software, however you instantiate the thing from many different courses. Virtually, you present a world level of entry to that occasion.

The intent is to have just one occasion of the category within the system, which makes it potential for different objects to entry it.

In all probability, you marvel why don’t you utilize a static class for this situation:

  • The benefit of the Singleton sample is that you should utilize the thing to cross to different strategies.
  • You should utilize the OOP ideas in Singleton courses.
  • A static class can’t be inherited.
  • You may dispose a singleton object. A static class can’t be disposed.
  • A singleton object is saved on the heap as a substitute of the stack. A static class is held on the stack.

Some actual situations if you want Singleton Sample

  • Once you desire a single connection to the database/server
  • To maintain a single entry level to the configuration. For instance, the SharedPreferences class in Android.
  • Single administration of expensive assets
  • For community connections

The way to implement the Singleton Sample in C#?

There are a number of methods to implement this sample, however a few of them have some disadvantages. The ultimate kind from this text is one of the best and is protected to make use of.

For every implementation, you’ll need to make the constructor non-public. You need to forbid the initialization of an object through the use of the constructor. We need to disguise the initialization of the thing. Virtually, we would like that the initialization to be inside. We obtain this step by making the constructor non-public. We may have a static technique that returns the occasion of the thing. Additionally, we’d like a personal static occasion of that object inside that class.

inside class ServerConnection
{
    non-public static ServerConnection _connection;
    non-public ServerConnection()
    {

    }

    public static ServerConnection GetServerConnection()
    {
        if (_connection==null)
        {
            _connection = new ServerConnection();
        }
        return _connection;

    }
}

Within the above code, you may see that contained in the static technique, we test to see if there’s already or not an occasion of that class. If there’s already an occasion, then it returns it. In any other case, it creates a brand new one.

An incredible benefit of the Singleton sample is lazy instantiation. Your occasion shall be first instantiated solely if you first name it.

Easy Singleton

That is the primary variant that you simply study.

The above code reveals you a easy Singleton sample. Please don’t use it! It is just for studying functions!

public static ServerConnection GetServerConnection()
{
    if (_connection==null) // thread 1 enters first and the situation is true. The thread would not but execute the under code that initialize the thread. The situation it is going to be nonetheless true for the second thread.
    {
        _connection = new ServerConnection(); // 
    }
    return _connection;
}

Easy doesn’t imply that that is the specified resolution. This technique is problematic when you name the GetInstance technique from a multi-thread software. There’s a huge chance that two threads will enter into the static technique that returns an occasion. Each will execute the if assertion, and since the mannequin shouldn’t be initialized, every will create a brand new one.

Thread Protected Singleton

A thread-safe Singleton is important. Neglect easy singleton!

On this case, I’ll use the lock assertion to make sure that just one thread checks the situation and initializes the thing.

inside sealed class ServerSafeSingleton 
{
    non-public static ServerSafeSingleton _serverInstace;
    non-public static object padLock = new object();

    non-public ServerSafeSingleton()
    {
    }
    public static ServerSafeSingleton GetServerConnection()
    {
        lock (padLock)
        {
            if (_serverInstace == null) // just one thread at a time can execute this line
            {
                _serverInstace = new ServerSafeSingleton();
            }

            return _serverInstace;
        }
    }
}

Thread Protected Singleton with out lock assertion

Right here is a straightforward resolution:

inside sealed class ServerSafeSingleton
{
    non-public static readonly ServerSafeSingleton _serverConnection= new ServerSafeSingleton();

    static ServerSafeSingleton()
    {
    }

    non-public ServerSafeSingleton()
    {
    }

    public static ServerSafeSingleton Occasion
    {
        get
        {
            return _serverConnection;
        }
    }
}

Singleton Sample Utilizing Lazy class

Lazy class to create objects utilizing lazy instantiation. So till the primary thread wants it, the thing shouldn’t be created. After the primary thread executes, the next threads will have already got an occasion.

inside sealed class ServerLazySingleton
 {
     non-public static readonly Lazy<ServerLazySingleton> lazy =
         new Lazy<ServerLazySingleton>(() => new ServerLazySingleton());

     public static ServerLazySingleton Occasion { get { return lazy.Worth; } }

     non-public ServerLazySingleton()
     {
     }
 }

Conclusions about Singleton Sample

I counsel you at all times to make use of the Singleton Sample, which is multi-thread protected. I normally prefer to implement the Singleton sample utilizing lock statements.

Don’t neglect that the Singleton sample is utilized in many tasks, so listen and discover ways to use it. In all probability, additionally, you will obtain interview questions on it. Listed here are the principle issues to recollect:

  • Personal constructor
  • A personal static member of that class
  • A static technique or property that returns the occasion
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments