如何根据客户在应用程序中选择策略

How to choose Strategy in an application depending on the Customer

在我工作的公司中,我们正在开发一个供各种客户(其他公司)使用的应用程序。应用程序的核心是相同的,但在某些细节方面,每个客户都有自己的要求。

我认为解决这个问题的方法是策略模式,通过向需要使用它的组件注入适当的策略。

我的问题是,有没有一种方法可以根据使用该应用程序的客户了解要注入哪个策略实施,而无需避免 "cases" 或 "if elses"?

您将如何在实际应用中实施它?

public IStrategy GetStrategy(string customerName) {
    switch(customerName) {
        case "customer1":
            return new Strategy1();
        case "customer2":
            return new Strategy2();
    }
}

编辑: 正如这个问题 (Strategy Pattern with no 'switch' statements?) 的公认答案所暗示的那样,"Strategy isn't a magic anti-switch solution.".

对此还有其他意见吗?

传递 strategyName 参数而不是 customerName 怎么样?我的意思是,如果您从数据库中检索您的 customerName,请为策略名称添加一列(它必须是策略 class 名称)。然后,使用该策略名称调用 GetStrategy 方法并使用 Activator.CreateInstance 方法创建策略 class 实例。

How to use Activator.CreateInstance (MSDN)

Activator.CreateInstance Example