Two integrated questions combined into one problem, about object hierarchy
TL:DR; I want to update nth level (great...-grand-)child object, but i have to find it through lots of iteration in objects in every level. Or to gain performance, I can keep a dict of this great-grand-children (skipping all in-between) and access them them directly but since I lost hierarchy, each target child should update it parents to keep them in up-to-date. Is a nice and clean pattern I could implement?
Here is an example that explains my question:
I have a building object, it has a list which has flats, each flat has list containing rooms, rooms also contain persons in a list. Like this:
building -> flats -> rooms -> persons
Each person sends a letter with unique code and waits for an answer with the same unique code. But building receives letters (a websocket that building listens). Traditionally it couldn't have been implemented like this:
apartment gets letter, iterates through each flat, each flat iterates their rooms, each room iterates through their persons, after finding its owner person, after person reads the letter, room updates itself, after room updates itself flat updates itself and returns done and breaks from for loops. But with hundreds of flats * rooms * persons, it will be extremely slow.
I'm thinking to solve it like this: building will keep a dictionary like {uniqueID: person} before sending the letter so when it receives a reply, I can use it like this:
if person := self.tracked_letters.get(received_letter.uniqueID, landlord):
person.read(received_letter)
This way if it is tracked letter it means it is a reply with senders unique code. so I can find this lowest level object, person, with the speed of a dict lookup. but skipping in-between objects forms second part of my question. This way, I can only access in-between via child, going upwards. Because of this I am passing self as a parameter when initializing every object, just for them to know their parent so they can update it after receiving letter.
This seemed like a ugly hack, apartment keeping persons info skipping flats, rooms in-between. Also persons, rooms should hold their parent's references etc., traditional method seems very slow. Is there any method or pattern I am missing here? Can you give me pointers or recommend a pattern/method?
Aucun commentaire:
Enregistrer un commentaire