Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat design pattern?
    text
    copied!<p>I have a class A maintaining a list of objects class B. But each object of class B can be referenced in any object of class A. Class B also maintains a list of objects of class A where it is being referenced. The program can and will create (several) objects of both class A and B 'at will' and also delete them.</p> <p>If I use C# I can add and delete objects from both classes with following code</p> <pre><code>public class A { private List&lt;B&gt;ListOfObjects_B; public bool Add(B Object) { bool bAdd = false; if ((Object != null) &amp;&amp; (ListOfObjects_B.IndexOf(B) &lt;0)) { ListOfObjects_B.Add(Object); Object.Add(this); bAdded = true; } return bAdded; } public bool Delete(B Object) { bool bDeleted = ListOfObjects_B.Remove(Object); if (bDeleted == true) Object.Delete(this); return bDeleted; } } public class B { private List&lt;A&gt;ListOfObjects_A; public bool Add(A Object) { bool bAdd = false; if ((Object != null) &amp;&amp; (ListOfObjects_A.IndexOf(A) &lt;0)) { ListOfObjects_A.Add(Object); Object.Add(this); bAdded = true; } return bAdded; } public bool Delete(A Object) { bool bDeleted = ListOfObjects_A.Remove(Object); if (bDeleted == true) Object.Delete(this); return bDeleted; } } </code></pre> <p>This will work as because of removing/adding the object to the ListOfObjects the SECOND time (by recursion) the function will be called it will fail to delete/add thereby avoiding an infinite loop.</p> <p>But I don't like this code even though A and B do not know 'much' about the other class and just call a Delete/Add function.</p> <p>I suppose this kind of problem is general and a design pattern exists for handling it in such a way that recursion can be avoided and updating both lists will be 'just better'. What design pattern should I use? I would appreciate if some code would be added as well. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload