How is OCP (Open closed principle) related to IoC (Inversion of Control)?

后端 未结 1 589
面向向阳花
面向向阳花 2021-01-22 16:15

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 c

相关标签:
1条回答
  • 2021-01-22 16:38

    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.

    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.

    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.

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

    0 讨论(0)
提交回复
热议问题