简体   繁体   中英

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. 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.

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. So now I have the original BigHierarchy object and the new one I need to merge. 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. 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.

For option 3, it would be wise to provide a merge function to all private members if that is possible. Rather I would mandate my objects to implement merge and invoke it passing the new object while doing merge.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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