StRoot  1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
SubjectObserver.cxx
1 //SubjectObserver.cxx
2 //M.L. Miller (Yale Software)
3 //11/01
4 
5 //std
6 #include "Stiostream.h"
7 using std::cout;
8 using std::endl;
9 #include <algorithm>
10 using std::find;
11 
12 //Sti
13 #include "SubjectObserver.h"
14 
15 Subject::Subject()
16 {
17  // cout <<"Subject::Subject()"<<endl;
18 }
19 
20 Subject::~Subject()
21 {
22  // cout <<"Subject::~Subject()"<<endl;
23  for (ObserverVec::iterator it=mObservers.begin(); it!=mObservers.end(); ++it) {
24  (*it)->forgetSubject(this);
25  }
26 }
27 
28 void Subject::attach(Observer* obs)
29 {
30  // cout <<"Subject::attach()"<<endl;
31  //check for existence before we add again:
32  ObserverVec::iterator where = find(mObservers.begin(), mObservers.end(), obs);
33  if (where==mObservers.end()) {
34  mObservers.push_back(obs);
35  }
36  else {
37  cout <<"Subject::attach(). ERROR:\t"
38  <<"observer already known to subject"<<endl;
39  }
40  // cout <<"\tSubject::attach() done"<<endl;
41 }
42 
43 void Subject::detach(Observer* obs)
44 {
45  // cout <<"Subject::detach()"<<endl;
46  ObserverVec::iterator where = find(mObservers.begin(), mObservers.end(), obs);
47  if (where!=mObservers.end()) {
48  mObservers.erase(where);
49  }
50  else {
51  cout <<"Subject::detach(). ERROR:\t"
52  <<"observer not known to subject"<<endl;
53  }
54  // cout <<"\tSubject::detach() done"<<endl;
55 }
56 
57 void Subject::notify()
58 {
59  //cout <<"Subject::notify()"<<endl;
60  for (ObserverVec::iterator it=mObservers.begin(); it!=mObservers.end(); ++it)
61  (*it)->changed(this);
62 }
63 
64 Observer::Observer()
65  : mSubject(0)
66 {}
67 
68 Observer::Observer(Subject * subject)
69  : mSubject(subject)
70 {}
71 
72 Observer::~Observer()
73 {}
74 
75 void Observer::changed(Subject* changedSubject)
76 {
77  //if (changedSubject!=mSubject)
78  // cout <<"Observer::changed(Subject*) - ERROR - changedSubject!=mSubject"<<endl;
79  //else
80  getNewState();
81 }