Design Patterns: Singleton

Characteristics 📚

  • Has only one object instance for the project
  • In many cases, it consider an anti-pattern

Hands-on 🤓

For the class that we want to involve with Singleton Pattern, we just include a private constructor and a method that return the existing instance:

public class Repository
{
private static IContext _context;
private Repository() { } public static IContext GetInstance()
{
if (_context is null)
{
_context = new Context.Context();
_context.OpenConnection();
}
return _context;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Singleton Sample...");
var repository1 = Repository.Repository.GetInstance();
var repository2 = Repository.Repository.GetInstance();
if (repository1 is not null && repository1.Equals(repository2))
Console.WriteLine("Singleton works.");
else
throw new InvalidOperationException("Singleton failed.");
}
}

Conclusion ✔

  • It’s too easy to implement.
  • The same class supports a multithread environment incorrectly. Because may be create many different instance

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store