OCP(开放式封闭原理)与IoC(控制反转)有何关系? [英] How is OCP (Open closed principle) related to IoC (Inversion of Control)?

查看:172
本文介绍了OCP(开放式封闭原理)与IoC(控制反转)有何关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能想到的一个例子是模板模式,这是一种做IoC的方法,也是OCP的一个例子.因为在模板模式中 我们定义了基本算法,子类无法更改该基本算法,但可以覆盖该算法的继承步骤方法.所以将来如果我们 要更改某个步骤的实现,我们可以创建另一个子类并实现这些步骤.

One example i can think of is Template Pattern which is a way of doing IoC is also an example of OCP. Because in template pattern we define the base algorithm which cannot be changed by child classes but can override the inherited step methods of that algorithm. So in future if we want to change the implementation of a step we can create another child class and implement those steps.

还有其他例子吗?

推荐答案

开放式原则建议您应该选择行为可扩展的东西,这样在需要它们做新的事情时就不必修改它们的源代码了.事情.

The open-closed principle suggests that you should prefer things with extensible behavior so that you don't have to modify their source code when you need them to do new things.

正确执行操作时,控制反转同时是提供这种可扩展性的最简单,最强大的方法.

When you do it right, inversion of control is simultaneously the simplest and most powerful way to provide this extensibility.

这是最简单的方式,因为当您为IoC定义可注入接口时,您仅捕获需求.其他配置可扩展行为的方法要求您考虑消费者可能想要的所有内容.

It's the simplest way, because when you define an injectible interface for IoC, you only capture your requirements. Other methods of configuring extensible behavior require you to think about everything consumers might want.

这是最强大的方式,因为代码可以执行任何操作,并且提供IoC扩展点允许使用者执行您未曾想到的所有事情,只要它们满足已定义的要求通过您的界面.同样,这是因为注入的接口只能捕获您自己的需求.

It's the most powerful way, because code can do anything, and providing an IoC extension point allows consumers to do all kinds of things you haven't imagined, so long as they satisfy the requirements defined by your interface. Again this is because the injected interface only captures your own needs.

因此,OCP和IoC的联系非常简单:OCP是目标,而IoC是实现目标的手段.

So, OCP and IoC are related in a very simple way: OCP is a goal, and IoC is the means to accomplish it.

这篇关于OCP(开放式封闭原理)与IoC(控制反转)有何关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆