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.
– Rovann Linhalis
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.
– Gabriel Coletta
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.
– pnet
You even looked at the related questions next door ---> ?
– rray
@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.
– pnet