简体   繁体   English

如何使用静态/单例设计模式来实现?

[英]How to implement this using static / singleton design pattern?

I want to implement a configuration helper. 我想实现一个配置助手。

The usage will be something like this: 用法将是这样的:

var companyName = ConfigHelper.Company.Name;
var redirectURL = ConfigHelper.URLs.DefaultRedirectURL; 

As you can see in the above examples, I have ConfigHelper which should not require an instance, however it will consist of sub classes (Company and URLs), and here I want access to the properties (not methods). 从上面的示例中可以看到,我有ConfigHelper,它不需要实例,但是它将由子类(公司和URL)组成,在这里我想访问属性(而不是方法)。

I want this all done without any class instances required, and not sure if I should be using static / singleton. 我希望所有这些都完成而无需任何类实例,并且不确定是否应该使用静态/单例。

I don't need exact code - but I guess a sample would be nice, rather just looking for a point in the right direction. 我不需要确切的代码-但我想一个示例会不错,而只是寻找正确方向的一点。

Thanks in advance. 提前致谢。

public static class Company
{
    public const string Name = "Company Name";
}

public static class ConfigHelper
{
    public static readonly Company = new Company();
}

Yes you're on the right track, ConfigHelper will be a static class and the properties will just be regular classes, but those will be instances. 是的,您在正确的道路上, ConfigHelper将是静态类,而属性将只是常规类,但这些是实例。

For example: 例如:

public class Company
{

    public string Name { get; set; }

}

public static class ConfigHelper
{

    static ConfigHelper()
    {
        Company = new Company();
    }

    public static Company Company { get; private set; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM