什么是静态属性和单身有什么区别? [英] what's the difference between static property and singleton?

查看:89
本文介绍了什么是静态属性和单身有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

辛格尔顿用C#实现的可能是这样的:

Singleton implemented with C# could be like:

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

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

如果我使用静态实现它像:

If I use static to implement it like:

public static class Globals{
  public static Singleton Instance = new Singleton();
}



以这种方式,应用程序也应该只获得一个实例为整个应用。
那么,这两个方法之间的区别? ?为什么不使用静态成员直接(更简单和直接的)

in this way, app should also only get the one instance for the entire app. So what's the difference between these 2 approaches? Why not use static member directly(more simple and straight forward)?

推荐答案

如果您使用第二种方式:

If you use the second approach:

public static class Globals{
  public static Singleton Instance = new Singleton();
}

有什么防止有人从做:

Singleton anotherInstance = new Singleton(); // Violates singleton rules

您还没有得到同样的延迟初始化你的第一个版本(尝试)实现,再加上你使用的是公共领域,它不允许你,如果你需要改变,当值取会发生什么未来同样的灵活性。

You also don't get the same lazy initialization your first version (attempts to) achieve, plus you're using a public field, which doesn't allow you the same flexibility in the future if you need to change what happens when a value is fetched.

需要注意的是.NET 4提供了潜在的更好的方法,使一个单:

Note that .NET 4 provides a potentially better approach to making a singleton:

public class Singleton
{
   private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton());

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         return instance.Value;
      }
   }
}

这是很好的,因为它是完全懒完全线程安全的,但也很简单。

This is nice because it's fully lazy and fully thread safe, but also simple.

这篇关于什么是静态属性和单身有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆