辛格尔顿属性 [英] Singleton Properties

查看:71
本文介绍了辛格尔顿属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,如果我创建一个单例类并通过公共静态属性公开单例对象……我理解。

Ok, if I create a singleton class and expose the singleton object through a public static property...I understand that.

但是我的单例类还有其他属性在里面。这些应该是静态的吗?这些也应该是私人的吗?

But my singleton class has other properties in it. Should those be static? Should those also be private?

我只想通过以下方式访问我的单例课程的所有属性:

I just want to be able to access all properties of my singleton class by doing this:

MySingletonClass.SingletonProperty.SomeProperty2

SingletonProperty向我返回单个单例实例。我想我的问题是,如何在singleton类中公开其他属性。.将它们设为私有,然后通过您的公共singleton静态属性访问它们?

Where SingletonProperty returns me the single singleton instance. I guess my question is, how do you expose the other properties in the singleton class..make them private and then access them through your public singleton static property?

还是应该

推荐答案

一旦获得,您的单例所有其他属性和方法就变为公共非静态的吗? SingletonProperty (这是一个对象的单个实例),此后的任何事情都可以实现,就好像您正在创建要实例化的类一样,因为Singleton实际上是常规对象的单个实例。

Once you get the SingletonProperty (which is the single instance of an Object), anything after that can be implemented as if you were creating a class to be instanciated because the Singleton is really a single instance of a regular Object.

例如,以下Singleton(显然不是最好的Singleton设计,但我愿意接受)提供了两个名为Value和Name的公共属性:

For example, the following Singleton (obviously not the best Singleton design, but bear with me) offers up two public Properties called Value and Name:

public class MySingleton
{
    private static MySingleton _instance;    

    private MySingleton() { }

    public static MySingleton Instance
    {
        get
        {
            if(_instance == null)
                _instance = new MySingleton();

            return _instance;
        }
    }

    // Your properties can then be whatever you want
    public string Value { get; set; }

    public string Name { get; set; }
}

访问这些属性如下:

MySingleton.Instance.Name = "StackOverflow";

MySingleton.Instance.Value = "Rocks!";

这篇关于辛格尔顿属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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