标签:11 cout Auto void AbstractFile ele stub
用透明组合模式实现教材中的“文件夹浏览”这个例子
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class AbstractFile {
public: virtual void add(AbstractFile *ele)=0;
virtual void remove(AbstractFile *ele)=0;
virtual void display()=0;
};
class TextFile :public AbstractFile{
private: string filename;
public: TextFile(string f) {
filename = f;
}
void add(AbstractFile *ele) {
// TODO Auto-generated method stub
cout<<"添加Text文件"<<endl;
}
void remove(AbstractFile *ele) {
// TODO Auto-generated method stub
cout<<"删除Text文件"<<endl;
}
void display() {
// TODO Auto-generated method stub
cout<<"展示Text文件"<< filename<<endl;
}
};
class ImageFile :public AbstractFile{
private: string filename;
public: ImageFile(string f) {
filename = f;
}
void add(AbstractFile *ele) {
// TODO Auto-generated method stub
cout << "添加Image文件" << endl;
}
void remove(AbstractFile *ele) {
// TODO Auto-generated method stub
cout << "删除Image文件" << endl;
}
void display() {
// TODO Auto-generated method stub
cout << "展示Image文件" << filename << endl;
}
};
class VideoFile :public AbstractFile{
private: string filename;
public: VideoFile(string f) {
filename = f;
}
void add(AbstractFile *ele) {
// TODO Auto-generated method stub
cout << "添加Video文件" << endl;
}
void remove(AbstractFile *ele) {
// TODO Auto-generated method stub
cout << "删除Video文件" << endl;
}
void display() {
// TODO Auto-generated method stub
cout << "展示Video文件" << filename << endl;
}
};
class Folder:public AbstractFile{
private: string filename;
private:vector<AbstractFile* > va;
public: Folder(string f) {
filename = f;
}
void add(AbstractFile *ele) {
// TODO Auto-generated method stub
va.push_back(ele);
cout<<"Folder add"<<endl;
}
void remove(AbstractFile *ele) {
// TODO Auto-generated method stub
vector<AbstractFile* >::iterator it;
it = find(va.begin(), va.end(), ele);
for (it != va.end();;){
va.erase(it);
}
cout<<"Folder remove"<<endl;
}
void display() {
// TODO Auto-generated method stub
for (vector<AbstractFile*>::const_iterator iter = va.begin(); iter != va.cend(); iter++) {
(*iter)->display();
}
cout<<"Folder:display"<<endl;
}
};
int main(){
AbstractFile *obj1, *obj2, *obj3, *obj4, *obj5;
Folder *plate1, *plate2, *plate3;
obj1 = new ImageFile("aaa.png");
obj2 = new TextFile("bbb.txt");
plate1 = new Folder("ccc");
plate1->add(obj1);
plate1->add(obj2);
obj3 = new VideoFile("ddd.mp3");
obj4 = new VideoFile("eee.mp3");
plate2 = new Folder("fff");
plate2->add(obj3);
plate2->add(obj4);
obj5 = new ImageFile("ggg.jpg");
plate3 = new Folder("hhh");
plate3->add(plate1);
plate3->add(plate2);
plate3->add(obj5);
plate3->display();
}
标签:11,
cout,
Auto,
void,
AbstractFile,
ele,
stub
From: https://www.cnblogs.com/YFLZ/p/17819405.html