C#应该Singleton包含静态方法吗?

时间:2016-10-02 12:21:35

标签: c# methods static singleton non-static

在为包含状态变量的类使用SingletonStatic之间进行选择时遇到很多麻烦。我希望类对象实例化并且只作为一个存在。

我知道两种方式都可以存储状态变量。 Static类似乎很容易处理变量,因为所有方法都将成为static,他们可以访问static变量而无需进一步的工作。

但是,Singleton的情况不同。我有两种方法;需要访问Singleton Instance变量的其他类型,以及无法访问Instance变量的其他变量,我可以将其标记为静态变量。

一个例子:

/// <summary>Singleton.</summary>
    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton(); /// <summary>Instance.</summary>
        public static Singleton Instance { get { return instance; } }

        private int integer; /// <summary>Integer.</summary>
        public int Integer { set { integer = value; } get { return integer; } }

        /// <summary>Constructor.</summary>
        private Singleton() { }

        /// <summary>TestA</summary>
        public void TestA(int val)
        {
            Integer = val;
        }

        /// <summary>TestB</summary>
        public static int TestB(int val)
        {
            return Instance.Integer * val;
        }

        /// <summary>TestC</summary>
        public static int TestC(int val)
        {
            return val * val;
        }
    }

从上面给出的例子中,有三种方法; TestATestBTestC

  1. TestA是一个non-static实例方法,可以访问其属性。
  2. TestBstatic方法,但访问Instance以获取其属性。
  3. TestC是实例无用的static方法。
  4. 这引出了一个问题:

    1. Singleton是否只包含static方法,并通过Instance static属性访问其Instance属性和方法?换句话说,所有方法都类似于TestBTestC
    2. Singleton是否只包含non-static种方法,无论是否需要Instance?所有方法与TestA类似。
    3. Singleton是否应包含混合staticnon-static(在这种情况下,TestATestB类)方法?我相信它会变得相当混乱。
    4. 如果没有,我该怎么办?我是否应该抛弃Singleton的想法,并且对于每个仅要实例化一次的类,请使用所有static
    5. 修改:对于类似问题,Singleton旁边是否应包含Static变量/字段/属性?

1 个答案:

答案 0 :(得分:3)

你不应该混淆这两种模式。

如果你有一个Singleton模式,唯一的静态字段应该是Instance(+ getter)。您应该可以通过实例访问所有方法和字段。如果你混淆它只会引起混淆。

如果选择静态类模式,请不要在.NET中使用秘密实例。

如果您不确定哪种模式最适合您,请查看此Singleton-vs-Static文章。它解释了两者的专业人士和对象:https://www.dotnetperls.com/singleton-static