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;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值