Design Standards: Singleton Design Standards

Asked

Viewed 597 times

1

I know that the Singleton guarantees me a single instance of a given object. I understood this. What creates doubt would be its use in practice like this. 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 a Requests form where I will post my orders. I will instantiate my Orders class Pedidos(T)? And the connection to the bank, how do I do? This is the question I have when implementing this Pattern. Where does the connection to the bank enter there?

  • from what I understand, if you use Singleton for requests, every time you call the class, the same request will be returned... you would have to clear the request and make another, because the instance of the object will already be created. I see no reason to use that for requests.

  • First, what is your goal of using a Singleton? Making a connection to the database is not recommended using a Singleton, so make a Connection pool.

  • That’s exactly what I wanted to read. In this test of mine, I need to implement at least one Pattern, and I thought of Singleton because I thought it was simpler, but I see that it’s not quite like that. I understood, remembering that I am undergoing a test and have a lot to be evaluated, among them, implement a Pattern.

  • You even looked at the related questions next door ---> ?

  • @rray, I read why we should not use Singleton, the colleague Maniero and was very well explained by the colleague utluiz. I’m reading yes, I always read when I ask questions about any subject.

1 answer

1


Usually we use the Singletonin one of the following situations:

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

For example, many people put the connection to the database within a Singleton so you don’t have to reconnect with the database every time you run a query. This way, the connection to the bank is made 1 time and remains active throughout the application lifecycle.

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

It is worth noting that the Singleton is often considered an antipattern, because it can harm the creation of unit tests and promotes a lot of class coupling (this is a bad thing in object orientation).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.