`open/closed 原则` 如何帮助避免重新部署程序集?

How `open/closed principle` can help avoiding to redeploy assemblies?

我最近读了一篇 nice, easy to understand article about open/closed principle。我对以下经历感到疑惑:

In a real world scenario where the code base is ten, a hundred or a thousand times larger and modifying the class means redeploying it’s assembly/package to five different servers that can be a pretty big problem. Oh, and in the real world Aldford would have changed the requirements five more times since you read the last sentence :-)

open/closed principle 如何帮助避免重新部署程序集?

如您所知,open/close 原则可以根据场景以不同的方式实现。 对于 后期绑定 的场景,open/close 原则意味着我要针对代码中可能发生此 minior/major 更改的部分的接口进行编程及时。

有关后期绑定的更多信息:https://en.wikipedia.org/wiki/Late_binding

在我提到的上下文中不久后绑定是能够在我们的程序中选择要在运行时加载的 dll。

我会试着用一个例子来解释。 如果我们的应用程序很大,而提供的功能的一小部分是进行一些计算(假设它添加数字)

ICalculator
{
    int Add(int a, int b);
}

包含计算器界面的dll是Application.Calcualtion.dll 并且在 dll 中使用 ICalculator 接口的代码可以有一些 Boostrapp/Init 函数来实例化计算器的具体实现。

后期绑定来了。

而不是使用 Calculator = new ConcreteCalculator() 之类的东西, 您可以从特定位置加载带有 ICalculator 接口实现的 dll。

using Assemnly.LoadFile(path: "....")

然后你可以使用类似这样的东西查询程序集的接口

var calculatorType = assembly.ExportedTypes.OfType<ICalculator>().Single();

通常可以从某个特定位置加载 dll。因此,当必须更改计算器实现时,应用程序的更新只能将具有 ICalculator 实现的新 dll 部署到您 boostrap dll 的特定位置。

后期绑定方法从另一个角度来看只是依赖倒置原则,而且还允许 extend/change 在不更改应用程序中的原始代码的情况下计算功能的行为。

希望对您有所帮助。