而不是使A級意識到每一個C類的,可以考慮使用Composite Pattern:
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <stdexcept>
//------------------------------------------------------------------------------
class Component
{
public:
typedef boost::ptr_vector<Component> Children;
virtual void print() = 0;
// Other operations
virtual bool isLeaf() {return true;}
virtual Children& children()
{throw std::logic_error("Leaves can't have children");}
};
//------------------------------------------------------------------------------
class Composite : public Component
{
public:
void print()
{
BOOST_FOREACH(Component& child, children_)
{
child.print();
}
}
bool isLeaf() {return false;}
Children& children() {return children_;}
private:
Children children_;
};
//------------------------------------------------------------------------------
class Nut : public Component
{
public:
Nut(std::string info) : info_(info) {}
void print() {std::cout << info_ << std::endl;}
private:
std::string info_;
};
//------------------------------------------------------------------------------
class Bolt : public Component
{
public:
Bolt(std::string info) : info_(info) {}
void print() {std::cout << info_ << std::endl;}
private:
std::string info_;
};
//------------------------------------------------------------------------------
class Wheel : public Composite
{
public:
Wheel(std::string info) : info_(info) {}
void print()
{
std::cout << info_ << std::endl;
Composite::print();
}
private:
std::string info_;
};
//------------------------------------------------------------------------------
class Vehicle : public Composite
{
public:
Vehicle(std::string info) : info_(info) {}
void print()
{
std::cout << info_ << std::endl;
Composite::print();
std::cout << "\n\n";
}
private:
std::string info_;
};
//------------------------------------------------------------------------------
int main()
{
Wheel* wheel1 = new Wheel("Wheel1");
wheel1->children().push_back(new Nut("Nut11"));
wheel1->children().push_back(new Nut("Nut12"));
wheel1->children().push_back(new Bolt("Bolt11"));
wheel1->children().push_back(new Bolt("Bolt12"));
Wheel* wheel2 = new Wheel("Wheel2");
wheel2->children().push_back(new Nut("Nut21"));
wheel2->children().push_back(new Nut("Nut22"));
wheel2->children().push_back(new Bolt("Bolt21"));
wheel2->children().push_back(new Bolt("Bolt22"));
Vehicle bike("Bike");
bike.children().push_back(wheel1);
bike.children().push_back(wheel2);
bike.print();
}
該程序的輸出:
Bike
Wheel1
Nut11
Nut12
Bolt11
Bolt12
Wheel2
Nut21
Nut22
Bolt21
Bolt22
注意,當bike.print()
被調用時,print
被稱爲遞歸地對所有的孩子。沒有父母知道所有孩子的情況下,你就可以對所有孩子進行操作。
Visitor Pattern在複合模式下效果很好,所以我建議你也閱讀一下。特別是如果你有許多操作可以用更基本的操作來實現。
我建議你通過「四人幫」來設計圖案書:http://en.wikipedia.org/wiki/Design_Patterns – 2010-05-26 14:28:09