我的系统目前运行在不同的环境中。
我的系统上有一个Environment枚举,就像这样
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或生产环境那样工作。
好吧,但是,有了这么多的配置,我可能会在我的枚举上有太多的maby属性,比方说,在3年内,每个枚举值将有15到20个属性,这看起来很奇怪。
你们觉得怎么样?你通常如何处理这种情况?它的属性真的太多了,还是没问题?
发布于 2012-11-14 20:49:30
使用private构造函数和描述环境所需的任意数量的属性创建一个Environment类,并将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);https://stackoverflow.com/questions/13379076
复制相似问题