Project Standards: Singleton

1

I know that Singleton guarantees me a single instance of a given object. I got this. What creates me doubt would be its use in practice like that. Let's assume the code below, using Singleton with Generics (code taken from the internet).

public sealed class Singleton<T> where T : class, new()
    {
        private static T instance;

        public static T Instance()
        {
            lock (typeof(T))
                if (instance == null) instance = new T();

            return instance;
        }
    }

I have an order form where I will post my orders. Will I instantiate my Pedidos(T) class? And the connection to the bank, how do I do it? That is the question I have when implementing this Pattern. Where does the connection to the bank come in?

    
asked by anonymous 08.12.2017 / 10:23

1 answer

1

Usually we use Singleton in one of the following situations:

  • Class consumes shared external resources
  • We want to avoid the overhead of instantiating the class in many different places

For example, many people put the database connection inside a Singleton so that they do not have to reconnect with the database every time they run a query. This way, the connection to the bank is made only once and remains active throughout the application's life cycle.

Another reason to use this pattern is when a class will be accessed in many places on the system and we do not want to abuse dependency injection. Log writing classes are sometimes implemented with Singleton so that you do not have to inject a log object into all system classes.

It's worth noting that Singleton is often considered an antipattern , as it can undermine the creation of unit tests and promotes a lot of coupling between classes (this is a bad thing in object orientation).

    
08.12.2017 / 12:51