Download presentation
Presentation is loading. Please wait.
Published byOsborn Reeves Modified over 9 years ago
1
The Trouble with Observer and Visitor Revisited PH Chapter 3 (pp. 72-85) Crystal Miller 03/22/06
2
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
3
OBSERVER Revisited Achieves MVC partitioning for user interfaces MODEL (SUBJECT) CONTROLLER VIEW (OBSERVER) State change View selection State query State change View selection
4
Composition of OBSERVER
6
Benefits Extend subjects/observers easily and independently Include/exclude certain presentation functionality No limit to number of observers for a particular subject Reusability
7
Composition of OBSERVER Drawbacks Run-time redundancy Static redundancy Major increase in classes
8
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.
9
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); }
10
VISITOR Revisited
11
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 (s); if (rs) { // add presentation code } else { // default Presenter::visit(s); }
12
VISITOR Revisited Adding new subjects (alternative) void RebateSubject::accept(Presenter& p){ NewPresenter* np = dynamic_cast (&p); if (np){ np->visit(this); } else{ Subject::accept(p); }
13
VISITOR Revisited Benefits Reduce number of classes Add new presentation functionality without modifying Subject’s code
14
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
15
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.