`

Observer Pattern

 
阅读更多

consistent communication model

 

for full article please refer to:

http://people.scs.carleton.ca/~ldnel/2404notes/330_patterns/GammaPatterns/Observer/

 


 

many dependent objects, and a subject which they are dependent on.

 

the trigger factor is the subject's state has changed

thus many registered(dependent) objects get notified by the subject

and then the registered observers(objects) quires the subject to synchronize its state with that of the subject's.

 

now i'm reading GOF design pattern observer part:

Mapping subjects to their observers. The simplest way for a subject to keep
track of the observers it should notify is to store references to them explicitly in
the subject. However, such storage may be too expensive when there are many
subjects and few observers. One solution is to trade space for time by using an
associative look-up (e.g., a hash table) to maintain the subject-to-observer
mapping. Thus a subject with no observers does not incur storage overhead. On
the other hand, this approach increases the cost of accessing the observers .

 

中文翻译:

 subject是观察者模式中的主体,即被观察者
 observer即观察者模式中的观察者
 在一个系统中 可以有多个subject对应多个observer
 他们之间是要保持关联关系的
 这种关系就是哪些observer观察哪些subject
 而这些关系的维护最简单的就是在subject中显式维护它的那些observer的引用
 就表明了它(subject)是受哪些observer观察的
 一旦发生情况,它只需要通知这些它维护的observers
 然而这样的存储在某种情况下太过昂贵,哪种情况呢 就是 many subjects and few observers
 即许多subjects,少许observers
 一种解决方案就是通过使用关联查找比如hash table来用空间换时间
 这样子来维护subject-to-observer的映射
 因此没有observer的subject也就不会引起存储花销
 但同时这种方法也增加了访问observer的花费

 


 

mine:

why on earth it doesn't incur storage overhead? originally, what does it do? how is it too expensive?

 

let's assume, originally if it directly stores references of observers in concrete subject, and in the case of many subjects few observers, more of those subjects may maintain a relationship. it thus causes  much more space expense than introducing ChangeManger. if using ChangeManager(associative look-up), more space will be used(the ChangeManager class), but lots of time will be saved, this is so called trade space for time . and in the situation of no observer, even no chman should be maintained in subject, it then does not incur storage overhead. and it will increase the cost of accessing the observers by looking up value by key than directly accessing the value(observer reference).

 

 

Added on 2012.11.17

观察者模式三要素

观察者,被观察者,观察事件

像这里:
Button.addActionListener(new ActionListener().........);

button就是被观察者
actionlistener就是观察者
观察事件是Action

而事件一般是在被观察者对象范围内发生的,因此往往当事件发生时,事件传递模式是由被观察者告知观察者,而之前,他们两者为了确立围绕某某事件的观察关系,需要所谓的“注册”。

 

 

 

 

 

 

 

  • 大小: 7.5 KB
  • 大小: 10.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics