如何编写符合 OCP 的代码?

发布于 2024-09-29 00:19:16 字数 237 浏览 2 评论 0原文

我最近一直在尝试学习基本的设计原理,但 OCP 让我有点困惑。当发生变化时,最好是扩展系统而不是修改现有的和工作的部分,这是有道理的。但这难道不是更多地是关于如何在系统中实施更改而不是如何设计系统的原则吗?不是所有代码基本上都可以通过使用子类来扩展吗?以及如何关闭任何代码以进行修改 - 这难道不只取决于实施更改的人如何选择使用它吗?

也许一些不遵循 OCP 的代码的示例以及它到底如何违反了该原则对我理解这一点最有帮助。

谢谢

I have recently been trying to learn about basic design principles and the OCP has me a bit confused. It makes sense that when a change happens it is preferable to extend the system rather than modify existing and working parts. But isn't this more of a principle for how to implement changes in a system rather than how to design one? Isn't all code basically open for extension by using subclassing? And how can any code be closed for modification - doesn't that just depend on how the person implementing a change chooses to use it?

Perhaps an example of some code that doesn't follow the OCP and how exactly it has violated the principle would be the most helpful for me to understand this.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送你一个梦 2024-10-06 00:19:16

一个典型的例子是任何在事物类型上分支的逻辑。
这样做意味着每次需要添加新类型时,都必须更改此代码。
使用虚函数意味着您只需为新类型添加新类,而无需更改现有代码。

开闭原则 (PDF)

里面有代码示例。

A typical example would be any logic that branches on the type of things.
Doing this means that every time you need to add a new type, you have to change this code.
Using virtual functions means that you can just add new classes for new types without changing existing code.

Open Closed Principle (PDF)

There are code examples in there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文