design-patterns - 过程和 OOP 封装

标签 design-patterns encapsulation

我搜索了关于封装概念的完整描述,发现找到的答案有点像拼图,必须拼在一起。我找到了这个概念的以下描述:

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. (source tutorialspoint)

A language mechanism for restricting access to some of the object's components A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data. (source wikipedia)

Encapsulation allows an object to separate its interface from its implementation. The data and the implementation code for the object are hidden behind its interface.

Encapsulation is a technique. It may or may not be for aiding in abstraction, but it is certainly about information hiding and/or organisation. It demands data and functions be grouped in some way - of course good OOP practice demands that they should be grouped by abstraction. However, there are other uses which just aid in
maintainability etc. (source stackoverflow)

在过程编程中,我认为主要是相同的,这里最好的例子是仅由文件函数创建或修改的 FILE 结构。

我想知道还可以添加什么来获得这个编程概念的完整图像,因为了解它在设计 API 或面试问题时非常有用。

最佳答案

你是对的:封装是一种允许实现信息隐藏原则的通用技术,因此可以在计算机科学的各个部分甚至其他领域中找到.

您已经提到了 FILE 指针。另一个简单的 C 示例是任何需要指向结构的指针而不声明它的 API。 接口(interface)用户不需要知道这个结构是如何实现的,只有接口(interface)实现需要知道。因此,通过将所需的操作(结构信息的传递)封装到传递指针的操作中来隐藏结构的信息。

另一个例子是网络协议(protocol):请求此页面时,您的浏览器使用 HTTP,而 HTTP 又使用传输控制协议(protocol) TCP。在下面的级别上,只有带有有效负载的互联网协议(protocol) IP,没有 TCP。在那里,TCP 只是封装在 IP 负载中的一些不需要的信息。在下一层,没有IP,只有MAC,IP是封装在MAC payload中的一些不需要的信息。

还有一个可能稍微牵强附会的现实例子: 通过邮件发送泰迪熊。您的邮政服务界面需要一个包含地址信息的框。它不会往盒子里看,也不会看到熊。当收件人收到包裹时,他会打开包裹,然后他就可以和小熊拥抱了。现在想象一下,邮政服务计划为您寄送泰迪熊。这个接口(interface)(bear + 地址)的可重用性如何?小的。相反,我们应用抽象并创建一个接口(interface)(框+地址)。我们通过将我们的泰迪熊放入盒子中来应用封装,隐藏我们实际发送泰迪熊的信息。可怜的泰迪。

关于design-patterns - 过程和 OOP 封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16645365/

相关文章:

c++ - 在不破坏封装的情况下访问功能替代品

c++ - 封装 vector

unit-testing - 什么是 ObjectMother?

java - Junit 和 java 类。

c# - 访问器关键字的 'fidelity' 是什么意思?

c# - 300条查找表存储数据的方法(c#)

java - java对象类型的正确封装是什么

java - 什么真正的java源代码实现了桥接模式?

java - 你应该在java中创建一个Generic Singleton类吗?

python - 从长度为 1 的元组中解压返回值