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

时间:2015-09-28 09:35:56

标签: c# domain-driven-design strategy-pattern

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

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

我的问题是,有没有办法知道根据使用该应用程序的客户注入哪种策略实施,而不是避免"案例"或者如果没有"?

您将如何在现实生活中应用它?

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

修改 正如这个问题的接受答案(Strategy Pattern with no 'switch' statements?)所暗示的那样,"策略并不是一种神奇的反转换解决方案。"。

还有其他意见吗?

1 个答案:

答案 0 :(得分:1)

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

How to use Activator.CreateInstance (MSDN)

Activator.CreateInstance Example