⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 composite_lab.cpp

📁 设计模式
💻 CPP
字号:
// Purpose.  Composite design pattern lab.//// Problem.  Approach is now more space efficient, but casting and type// checking are required to coerce the compiler.  The abstraction needs to// be improved so that Primitive and Composite can be treated// transparently in a sibling context, while still maintaining their// specialization.//// Assignment.// o Create a class Component to serve as a base class.  Primitive and//   Composite should inherit from Component.// o Move anything that is (or needs to be) common in both Primitive and//   Composite up into Component.// o Currently class Composite is coupled to itself (the argument to add() and//   the children private data member).  It needs to be coupled only to its//   abstract base class.// o You can now remove: NodeType, reportType(), the casting in main() and//   Composite::traverse(), and the "type checking" in Composite::traverse()#include <iostream.h>enum NodeType { LEAF, INTERIOR };
class Component {
public:
	Component( int _value, NodeType _type) { value = _value ; type = _type; }
	NodeType reportType()                  { return type; }
	virtual void add(Component *c)         {}
	virtual void traverse()                {}
	int getValue()                         { return value; }
	NodeType getType()                     { return type;  } 
private:
	int       value;
	NodeType  type;
};
class Primitive : public Component {public:   Primitive( int val ) : Component(val,LEAF)     { }   NodeType reportType()                          { return Component::getType(); }   void     traverse()                            { cout << Component::getValue() << " "; }private:};class Composite : public Component {public:   Composite( int val ) : Component(val,INTERIOR)     { total = 0; }   NodeType reportType()                              { return Component::getType(); }   void     add( Component * c )                       { children[total++] = c; }   void traverse() {	   cout << Component::getValue() << " ";      for (int i=0; i < total; i++)         if (children[i]->reportType() == LEAF)            ((Primitive*) children[i])->traverse();         else               children[i]->traverse();   }private:   int         total;   Component*  children[99];};void main( void ) {   Composite  first(1), second(2), third(3);
   first.add( &second );
   first.add( &third );
   first.add( new Primitive(4) );
   second.add( new Primitive(5) );
   second.add( new Primitive(6) );
   third.add( new Primitive(7) );
   first.traverse();
   cout << endl;
}// 1 2 5 6 3 7 4

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -