17 Aralık 2017 Pazar

C# Singleton Örnekleri

Örnek
Tüm alanları static yaparak şöyle yaparız. Bu sanırım en kötü Singleton çeşidi.
public static class DataManager
{
  public static int a = 0;
  public static int b = 0;
  public static int c = 0;
}
Örnek - Thread safe ama lazy değil
Şöyle yaparız.
public class DataManager
{

  private static DataManager _sharedInstance = new DataManager();

  static internal DataManager SharedInstance()
  {
    return _sharedInstance;
  }
  ...

}
Örnek - Thread safe değil
Şöyle yaparız.
// Bad code! Do not use!
public sealed class Singleton
{
  private static Singleton instance=null;

  private Singleton()
  {
  }

  public static Singleton Instance
  {
    get
    {
      if (instance==null)
      {
        instance = new Singleton();
      }
      return instance;
    }
  }
}


Hiç yorum yok:

Yorum Gönder