数据结构:有什么像双向观察者模式吗? [英] Data structure: Is there something like a two way observer pattern?

查看:124
本文介绍了数据结构:有什么像双向观察者模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类似这样的课程学生和课程



学生A注册在课程1,2



学生B注册在课程1,2,3,



学生C已加入课程2



所以有两种事件:



学生A被删除 - >需要通知两个对象:课程1和课程2



课程1被取消 - >需要通知两个对象:学生A和学生B



我知道Observer模式可以工作,如果每个学生只能参加1门课程,在这种情况下,我在Observer模式中列出了每个课程对象的学生。



我想知道我是否应该做两点方式观察者模式(学生保留课程列表,课程还保留学生名单)。那么这将是处理这个问题的好方法?主要关注的是速度/空间的折中(我现在可以想到的是从1名学生到1套课程和1套课程到1套学生的双向哈希/树)。任何指针都将不胜感激!

解决方案

您真正要问的是域模型中的级联语义。例如,如果课程被删除,学生是否被删除?当然不是。如果学生被删除,课程是否被删除? No。



我想你可能想要考虑的是另一个类:注册。学生A在日期Y注册了课程X,然后如果课程被取消,您将级联删除注册,然后当您去学生看看他注册了什么时,您没有看到该课程了。 p>

这个策略的额外好处是,如果你想保留信息(他被注册了,课程被取消),那就是注册类(这是在协会类)。


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

解决方案

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

这篇关于数据结构:有什么像双向观察者模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆