> For the complete documentation index, see [llms.txt](https://haoqinn.gitbook.io/handbook-of-design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://haoqinn.gitbook.io/handbook-of-design-pattern/she-ji-mo-shi-yuan-ze/untitled-4.md).

# 开放封闭原则

## 开放和封闭

当需要改变一个程序的功能或者给这个程序增加新功能的时候，可以使用增加代码的方式，但是不允许改动程序的源代码

例如我们都知道的关于肥皂的故事：

> 有一家生产肥皂的大企业，从欧洲花巨资引入了一条生产线。这条生产线可以自动 完成从原材料加工到包装成箱的整个流程，但美中不足的是，生产出来的肥皂有一定的 空盒几率。于是老板又从欧洲找来一支专家团队，花费数百万元改造这一生产线，终于 解决了生产出空盒肥皂的问题。
>
> 另一家企业也引入了这条生产线，他们同样遇到了空盒肥皂的问题。但他们的解决 办法很简单:用一个大风扇在生产线旁边吹，空盒肥皂就会被吹走。

所以相比于修改源程序，如果通过增加几行代码就能解决问题，这显然更加简单和优雅，而且增加代码并不会影响原系统的稳定性。

## 小结

实际上，让程序保持完全封闭是不容易做到的。就算技术上做得到，也需要花费太多的时间和精力。而且让程序符合开放-封闭原则的代价是引入更多的抽象层次，更多的抽象有可能会增大代码的复杂度，而且有一些代码是无论如何也不能完全封闭的，总会存在一些无法对其封闭的变化，因此我们只需要**挑出最容易发生变化的地方，然后构造函数来封闭这些变化**，而且在不可避免发生修改的时候，尽量**修改那些相对容易修改的地方，就比如一个开源库，修改它提供的配置文件总比修改它的源代码来的简单**

在程序一开始就尽量遵守开放-封闭原则并不是一件容易的事情，而且有时候需求排期不会让你有那么多时间去想一些未来的事情，所以我们在最初编写代码的时候，先假设变化永远不会发生，这有利于我们迅速完成需求。当变化发生并且对我们接下来的工作造成影响的时候可以再回过头来封装这些变化的地方


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://haoqinn.gitbook.io/handbook-of-design-pattern/she-ji-mo-shi-yuan-ze/untitled-4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
