1

我的系统目前在不同的环境中运行。

我的系统上有一个环境枚举,像这样

public enum Environment {

    [UsePayPal(false)]
    [ServerInstallDir("InstallPathOnServer")]
    [IntegrationSystemURI("localhost/someFakeURI")]
    [UpdateSomeInfo(true)]
    [QueuePrefix("DEV")]
    [UseCache(false)]
    [AnotherSystemURI("localhost/anotherFakeURI")]
    Development = 0,

    [UsePayPal(false)]
    [ServerInstallDir("InstallPathOnBUILDServer")]
    [IntegrationSystemURI("build-server/someFakeURI")]
    [UpdateSomeInfo(true)]
    [QueuePrefix("QA")]
    [UseCache(false)]
    [AnotherSystemURI("build-server/anotherFakeURI")]
    QA = 1,

    [UsePayPal(true)]
    [ServerInstallDir("InstallPathOnServer")]
    [IntegrationSystemURI("someservice.com/URI")]
    [UpdateSomeInfo(true)]
    [QueuePrefix("PRD")]
    [UseCache(true)]
    [AnotherSystemURI("anotherservice/URI")]
    Production = 2,
}

我正在这样工作,因为我不喜欢这样的代码

if(CURRENT_ENVIRONMENT == Environment.QA || CURRENT_ENVIRONMENT == Environment.DEV)
    EnableCache()

或者

if(CURRENT_ENVIRONMENT == Environment.QA || CURRENT_ENVIRONMENT == Environment.DEV){
    DoSomeStuff();
}

因为我认为这将我的逻辑分散在整个系统中,而不是在一个点上。

如果有一天我添加了另一个测试环境,我不需要检查我的代码来查看我是否像在开发、QA 或生产环境中工作一样。

好的,但是,通过所有这些配置,我最终可能会在我的 Enum 上获得过多的属性,比如说,在 3 年内每个枚举值将有 15~20 个属性,这看起来很奇怪。

你们有什么感想?你通常如何处理这种情况?它的属性真的太多了,还是这样?

4

1 回答 1

3

创建一个Environment具有private构造函数和描述环境所需的尽可能多的属性的类,并将static readonly实例公开为公共属性。您还可以拥有Environment.Current指向这些实例之一的属性。

示例代码:

sealed class Environment
{
    // The current environment is going to be one of these -- 1:1 mapping to enum values
    // You might also make these properties if there's fine print pointing towards that
    public static readonly Environment TestEnvironment;
    public static readonly Environment ProductionEnvironment;

    // Access the environment through this
    public static Environment Current { get; set; }

    static Environment()
    {
        TestEnvironment = new Environment {
            UsePayPal = false,
            ServerInstallDir = "/test"
        };
        ProductionEnvironment = new Environment { 
            UsePayPal = true, 
            ServerInstallDir = "/prod"
        };
    }

    // Environment propeties here:
    public bool UsePayPal { get; private set; }
    public string ServerInstallDir { get; private set; }

    // We don't want anyone to create "unauthorized" instances of Environment
    private Environment() {}
}

像这样使用它:

Environment.Current = Environment.TestEnvironment;

// later on...
Console.WriteLine(Environment.Current.ServerInstallDir);
于 2012-11-14T12:49:29.723 回答