AlexLecture_CaseStudyCompositeVisitor - 1 Case Study...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 Case Study: Composite Pattern + Visitor Pattern “is-a” cannot via private/protected Will this compile? #include <iostream> using namespace std; class A { private: int foo; public: A(int f) : foo(f) {}; void print() { cout << foo << endl; } }; Avoid private/protected inheritance Defining class B by privately inheriting from class A is almost always equivalent to giving B a private data member of A. Same to protected inheritance. #include <iostream> using namespace std; class B { public: B(int f) : a(f) {}; void p2() { a.print(); } 2 class B : private A { public: B(int f) : A(f) {}; void p2() { A::print(); } }; int main(void){ A a(3); B b(4); a.print(); b.print(); b.p2(); } Alex X. Liu private: A a; }; Will upcasting allow us to call b.print()? Answer: NO. We cannot upcast an object of B to an object of A due to private inheritance. A* pa = &b; // error: 'A' is an inaccessible base of 'B'. Review: Composite Pattern Client Component Operation() Composite Lea children * * 3 Alex X. Liu Composite Operation() Add(Component) Remove(Component) GetChild(int) : Component Leaf Operation() forall g in children g.Operation(); Review: Visitor Pattern 4 Alex X. Liu Recipe – Element and ConcreteElement class Element{ public: virtual void Accept(Visitor&) = 0; }; class ConcreteElementA : public Element { public: 5 Alex X. Liu virtual void Accept(Visitor& v) { v.VisitConcreteElementA(this); } }; class ConcreteCompositeA : public Element { public: virtual void Accept(Visitor& v) { v.VisitConcreteCompositeA(this); } Recipe – Visitor and ConcreteVisitor class Visitor { public: virtual void VisitConcreteElementA(ConcreteElementA*)=0; virtual void VisitConcreteCompositeA(ConcreteCompositeA *)=0; }; class ConcreteVisitorA : public Visitor{ public: 6 Alex X. Liu virtual void VisitConcreteElementA(ConcreteElementA* ela) { //may store something in the state variables; }; virtual void VisitConcreteCompositeA(ConcreteCompositeA *cela) { forall children g do g->accept(this); //may change state variables values based on their value}; getVisitResult() {…}; private: //state variables for storing visit results. For example, a stack, for a tree visitor....
View Full Document

Page1 / 3

AlexLecture_CaseStudyCompositeVisitor - 1 Case Study...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online