23种设计模式之组合模式(结构型,5 Composite,c++实现)
代码实现:
#include <iostream>
#include <list>
#include <string>
using namespace std;
class IFile
{
public:
virtual void display() = 0;
virtual int add(IFile*) = 0;
virtual int remove(IFile*) = 0;
virtual list<IFile*>* getChildren() = 0;
};
class File : public IFile
{
public:
File(string name)
{
this->name = name;
}
virtual void display()
{
cout << name << endl;
}
virtual int add(IFile* file)
{
return -1;
}
virtual int remove(IFile* file)
{
return -1;
}
virtual list<IFile*>* getChildren()
{
return NULL;
private:}
string name;
};
class Dir : public IFile
{
public:
Dir(string name)
{
this->name = name;
this->_list = new list<IFile*>;
}
virtual void display()
{
cout << name << endl;
}
virtual int add(IFile* file)
{
_list->push_back(file);
return 0;
}
virtual int remove(IFile* file)
{
_list->remove(file);
return 0;
}
virtual list<IFile*>* getChildren()
{
return _list;
}
private:
list<IFile*>* _list;
string name;
};
void showTree(IFile* root, int level)
{
if (root == NULL)
{
return;
}
for (int i = 0; i < level; i++)
{
printf("\t");
}
root->display();
list<IFile*>* children = root->getChildren();
if (children != NULL)
{
for (list<IFile*>::iterator it = children->begin(); it != children->end(); it++)
{
if ((*it)->getChildren() != NULL)
{
showTree(*it, level + 1);
}
else
{
for (int i = 0; i < level + 1; i++)
{
printf("\t");
}
(*it)->display();
}
}
}
}
void main()
{
IFile* root = new Dir("C");
IFile* dir1 = new Dir("dir1");
IFile* aaaFile = new File("aaa.txt");
root->add(dir1);
root->add(aaaFile);
root->display();
list<IFile*>* children = root->getChildren();
for (list<IFile*>::iterator it = children->begin(); it != children->end(); it++)
{
(*it)->display();
}
IFile* dir2 = new Dir("dir2");
IFile* bbbFile = new File("bbb.txt");
dir1->add(dir2);
dir1->add(bbbFile);
showTree(root, 0);
delete dir1;
delete dir2;
delete root;
delete aaaFile;
delete bbbFile;
}