150 likes | 229 Views
The Trouble with Observer and Visitor Revisited . PH Chapter 3 (pp. 72-85) Crystal Miller 03/22/06. OBSERVER Revisited. Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. MODEL (SUBJECT).
E N D
The Trouble with Observerand Visitor Revisited PH Chapter 3 (pp. 72-85) Crystal Miller 03/22/06
OBSERVER Revisited • Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
MODEL (SUBJECT) CONTROLLER VIEW (OBSERVER) State change State query State change View selection View selection OBSERVER Revisited • Achieves MVC partitioning for user interfaces
Composition of OBSERVER • Benefits • Extend subjects/observers easily and independently • Include/exclude certain presentation functionality • No limit to number of observers for a particular subject • Reusability
Composition of OBSERVER • Drawbacks • Run-time redundancy • Static redundancy • Major increase in classes
VISITOR Revisited • Intent: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
VISITOR Revisited class Presenter { public: Presenter(); virtual void visit(LoanSubject*); virtual void visit(AmountSubject*); virtual void visit(RateSubject*); virtual void visit(PeriodSubject*); virtual void visit(Subject*); //default presentation virtual void init(Subject*); //initial state virtual void draw(Window*, Subject*); //draw UI virtual void handle(Event*, Subject*); //user input }; void LoanSubject::accept (Presenter& p){ p.visit(this); }
VISITOR Revisited • Adding new subjects • If new subject does default behavior void RebateSubject::accept(Presenter& p) { p.visit(this); } • If new subject has a special presentation(s) • Subclass Presenter void NewPresenter::visit(Subject* s){ RebateSubject* rs=dynamic_cast<RebateSubject*>(s); if (rs) { // add presentation code } else { // default Presenter::visit(s); }
VISITOR Revisited • Adding new subjects (alternative) void RebateSubject::accept(Presenter& p){ NewPresenter* np = dynamic_cast<NewPresenter*>(&p); if (np){ np->visit(this); } else{ Subject::accept(p); }
VISITOR Revisited • Benefits • Reduce number of classes • Add new presentation functionality without modifying Subject’s code
VISITOR Revisited • Drawbacks • Presenter class can become a monolith • Decomposing it restores initial issue of too many Observer objects • Not extremely easy to add new subjects
Author Disclaimer • WARNING: This section contains speculative designs that are provided on an “as-is” basis. The author and publisher make no warranty of any kind, expressed or implied, regarding these designs. But feel free to bet your career on them anyway.