Data structure: Is there something like a two way observer pattern?

我与影子孤独终老i 提交于 2019-12-13 06:01:11

问题


So I have a scenario like this with classes Student and Course

Student A is enrolled in Course 1, 2

Student B is enrolled in Course 1, 2, 3

Student C is enrolled in Course 2

So there are two kinds of events:

Student A is deleted -> need to notify two objects: Course 1 and Course 2

Course 1 is canceled -> need to notify two objects: Student A and Student B

I know that the Observer pattern can work if each Student can be only enrolled in 1 Course, in which case I have a list of Student for each Course object in the Observer Pattern.

I am wondering if I should do some two way Observer Pattern (Student keeps a list of Courses and the Course also keeps a list of students). So would be a good way to deal with this problem? Main concern is speed/space tradeoff (what I can think of at best now is a two way hash/tree from 1 Student to 1 set of Courses and 1 Course to 1 set of Students). Any pointer will be appreciated!!


回答1:


What you are really asking about is cascade semantics in a domain model. For instance, if a Course is deleted, should the students be deleted? Of course not. If a Student is deleted, should the Course be deleted? No.

I think what you might want to consider is another class: Enrollment. That says Student A enrolled in Course X on Date Y. Then if a course is Canceled, you cascade delete the Enrollments and then when you go to that Student to see what he's enrolled in, you don't see that Course anymore.

The additional benefit of this strategy is that if you want to retain the information (that he was enrolled and the Course was cancelled), that is there in the Enrollment class (which is an Association class).



来源:https://stackoverflow.com/questions/14594602/data-structure-is-there-something-like-a-two-way-observer-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!