简体   繁体   中英

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).

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.

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; }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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