A lot of people think that this is bad design pattern, because it has some disadvantages. But sometimes, in rare cases using of Singletone pattern is useful. Let’s talk about this pattern on example.
We have api connector that should be initiated only one time. In other cases we have to return instance of connector. How can we do it?
public class ApiConnector
{
public string id;
private ApiConnector()
{
Console.WriteLine("Connected!");
id = System.Guid.NewGuid().ToString();
}
private static Lazy<ApiConnector> instance = new Lazy<ApiConnector>(() =>
{
return new ApiConnector();
});
public static ApiConnector Instance => instance.Value;
}
We created ApiConnector class with static method, that creates instance when we have first request and then our class returns ready instance. Let’s see it.
ApiConnector apiConnector = ApiConnector.Instance;
Console.WriteLine($"Database ID: {apiConnector.id}");
ApiConnector apiConnector2 = ApiConnector.Instance;
Console.WriteLine($"Database ID: {apiConnector2.id}");
What do you think about results? What Id’s we receive? Different or the same? Let’s see!
Connected!
Database ID: afab53b8-0fdb-4d77-bd96-1c4e1c354cac
Database ID: afab53b8-0fdb-4d77-bd96-1c4e1c354cac