简体   繁体   English

添加到我的程序中的导入功能破坏了OOP封装。 如何恢复封装?

[英]Import feature added to my program breaks OOP encapsulation. How do I restore encapsulation?

I have a program that stores it's information in an XML file. 我有一个程序将其信息存储在XML文件中。 This file is read in and a corresponding object model is created. 读取该文件,并创建相应的对象模型。 The object model has a tree hierarchy. 对象模型具有树层次结构。 The object type we'll call BigHierarchy. 我们将对象类型称为BigHierarchy。

Now, my program has a feature that allows the user to import another file. 现在,我的程序具有允许用户导入另一个文件的功能。 So, when he selects the file he wishes to import I read in that file and construct an another object of type BigHierarchy to represent the import file. 因此,当他选择他要导入的文件时,我读了该文件,并构造了另一个BigHierarchy类型的对象来表示导入文件。 So now I have the original BigHierarchy object and the new one I need to merge. 因此,现在我有了原始的BigHierarchy对象和需要合并的新对象。 Since it's a hierarchy, some of the data is private and not accessible. 由于它是一个层次结构,因此某些数据是私有的并且不可访问。

How do I go about merging the import object with the original object if I don't have access to the private data? 如果我无权访问私有数据,该如何将导入对象与原始对象合并? What technique should I use? 我应该使用什么技术? Should the leaf nodes friend the higher ups so I have full visibility from the top? 叶子节点是否应该与更高的朋友打交道,这样我就可以从顶部完全看到它们? Should I add overload all the leafs and overload plus operator so I can merge everything or should I make member functions in each level that copies all the private data. 我应该添加重载所有叶子和重载加运算符,以便可以合并所有内容,还是应该在复制所有私有数据的每个级别中使用成员函数。 Every option seems messy. 每个选项似乎都很混乱。 How do I go about this in the best way? 我该如何以最好的方式做到这一点?

To get to the exact design you need to first define what would be your merge strategy in case there is a conflict between private members at their most atomic level. 为了进行精确的设计,您需要首先定义什么是合并策略,以防私有成员之间在其最原子级别上发生冲突。

  1. Overwrite with latest 用最新覆盖
  2. Keep original 保持原始
  3. Merge the changes 合并变更

If you go with approach 1, then you will overwrite the existing BigHierarchy with new one. 如果采用方法1,则将用新方法覆盖现有的BigHierarchy。 In this case you will need access methods which allow setting the private members. 在这种情况下,您将需要允许设置私有成员的访问方法。 This way encapsulation will not get affected. 这样封装不会受到影响。

If you choose approach 2, then you will not be touching the private members at all. 如果您选择方法2,那么您将根本不会碰私人成员。

For option 3, it would be wise to provide a merge function to all private members if that is possible. 对于选项3,如果可能的话,向所有私有成员提供合并功能是明智的。 Rather I would mandate my objects to implement merge and invoke it passing the new object while doing merge. 相反,我将授权我的对象实现合并,并在合并时通过新对象调用它。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM