'Design pattern for classes with parent-children relation that will keep attributes on both instances up to date?
Is there a Pythonic design pattern which would tell me how to handle a one-to-many (parent-children) relationship on objects? I have a few different classes linked to each other (so it's not a simple tree), but to keep it simple let's assume I have classes Container and Element.
class Container:
elements: List[Element]
class Element:
container: Container
Let's assume a situation like this happens:
my_container = Container(elements=[])
my_element = Element(container=container) # at this point I expect that my_container will add `my_element` to its `elements` list.
my_container.elements = [] # at this point I expect that my_element.container will change to None.
I see that I can use getters and setters, but there are quite a lot of edge cases to handle - for example deleting objects, initializing new objects etc. I feel like this is some boilerplate and I'm reinventing the wheel. Do you know of any tool/design pattern/tutorial about how to handle such situations?
Solution 1:[1]
You could consider using an observer pattern, so that element objects subscribe to the container when they are added, and when the container is modified of cleared to remove an element, that element is notified that is was removed.
When it comes to design patterns, there's no one answer, but an observer pattern looks pretty logical for this scenario.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Miguel Guthridge |
