每日博客

[实验任务一]:组合模式

用透明组合模式实现教材中的“文件夹浏览”这个例子。

实验要求:

1. 文件的执行不需真正实现,只需简单提示即可;

 

 

2. 提交源代码;

#include <iostream>

#include <string>

#include <list>

using namespace std;

 

class Component

{

protected:

string name;

public:

Component(string name)

:name(name)

{ }

virtual void AddComponent(Component *component) { }

virtual void RemoveComponent(Component *component) { }

virtual void GetChild(int depth) { }

};

 

class Leaf: public Component

{

public:

Leaf(string name)

:Component(name)

{ }

void AddComponent(Component *component)

{

cout<<"can't add"<<endl;

}

void RemoveComponent(Component *component)

{

cout<<"can't remove"<<endl;

}

void GetChild(int depth)

{

string _tmpstring(depth, '-');

cout<<_tmpstring<<name<<endl;

}

};

 

class Composite:public Component

{

private:

list<Component*> _componets;

 

public:

Composite(string name)

:Component(name)

{ }

void AddComponent(Component *component)

{

_componets.push_back(component);

}

void RemoveComponent(Component *component)

{

_componets.remove(component);

}

void GetChild(int depth)

{

string tmpstring (depth, '-');

cout<<tmpstring<<name<<endl;

list<Component*>::iterator iter = _componets.begin();

for(; iter != _componets.end(); iter++)

{

(*iter)->GetChild(depth + 2);

}

}

};

 

main()

{

Composite *root = new Composite("root");

Leaf *leaf1 = new Leaf("A");

Leaf *leaf2 = new Leaf("B");

root->AddComponent(leaf1);

root->AddComponent(leaf2);

 

Composite *lay2 = new Composite("AA");

Leaf *leaf4 = new Leaf("BB");

lay2->AddComponent(leaf4);

 

Composite *lay1 = new Composite("CC");

Leaf *leaf3 = new Leaf("C");

lay1->AddComponent(leaf3);

lay1->AddComponent(lay2);

 

root->AddComponent(lay1);

 

root->GetChild(1);

cout<<endl;

lay1->GetChild(1);

cout<<endl;

lay2->GetChild(1);

 

delete root;

delete lay1;

delete lay2;

delete leaf1;

delete leaf2;

delete leaf3;

delete leaf4;

}

 

3.注意编程规范。

 

 

posted @ 2024-02-13 08:40  秃头的小白  阅读(9)  评论(0编辑  收藏  举报