namespace DesignPattern_Composite { class Component { public: virtual void operation() = 0 ; virtual void Add(Component*) {} } ; class AbstractComponent1 : virtual public Component {} ; class AbstractLeaf1 : virtual public AbstractComponent1 {} ; class Composite1 : public AbstractComponent1 { public: virtual void operation() { /* do operation */ } virtual void Add(Component*) ; } ; void Composite1::Add(Component *p) { AbstractComponent1 *pc1 = dynamic_cast<ABSTRACTCOMPONENT1*>(p) ; if (pc1 == NULL) return ; // do add operation } class AbstractComponent2 : virtual public Component {} ; class AbstractLeaf2 : virtual public AbstractComponent2 {} ; class Composite2 : public AbstractComponent2 { public: virtual void operation() { /* do operation */ } virtual void Add(Component*) ; } ; void Composite2::Add(Component *p) { AbstractComponent2 *pc2 = dynamic_cast<ABSTRACTCOMPONENT2*>(p) ; if (pc2 == NULL) return ; // do add operation } class ConcreteLeaf1 : public AbstractLeaf1 { public: virtual void operation() { /* do operation */ } } ; class ConcreteLeaf2 : public AbstractLeaf1, public AbstractLeaf2 { public: virtual void operation() { /* do operation */ } } ; } 客户端代码: { using namespace DesignPattern_Composite ; Component *pc1 = new ConcreteLeaf1() ; Component *pc2 = new ConcreteLeaf2() ; Component *pc3 = new Composite1() ; Component *pc4 = new Composite2() ; pc3->Add(pc1) ; // ok pc3->Add(pc2) ; // ok pc3->Add(pc3) ; // ok pc3->Add(pc4) ; // fail pc4->Add(pc1) ; // fail pc4->Add(pc2) ; // ok pc4->Add(pc3) ; // fail pc4->Add(pc4) ; // ok } |