C++ 组合模式


#include 
#include 
#include 
#include 
using namespace std;
class IFile
{
public:

    virtual ~IFile(){}
    virtual void show() = 0;
    virtual void add(IFile *f) = 0;
    virtual void remove(IFile *f) = 0;
    virtual list* Getchild() = 0;
    virtual string getname() = 0;
};
class File:public IFile
{
public:
    File(string name)
    {
        m_name  = name;
    }
    string getname()
    {
        return m_name;
    }

    void show()
    {
        cout<* Getchild()
    {
        return nullptr;
    }

private:
    string m_name;
};


class Dir:public IFile
{
public:
    Dir(string name)
    {
        m_name  = name;
        _list = new list;

    }
    ~Dir()
    {
      if(_list!=NULL)
      {

        while(!_list->empty())
        {
            delete *(_list->begin());
            _list->erase(_list->begin());

        }
        delete _list;
      }
    }
    string getname()
    {
        return m_name;
    }
    void show()
    {
        cout<push_back(f);
    }
    void remove(IFile *f)
    {
        _list->remove(f);
    }
    list* Getchild()
    {
        return _list;
    }

private:
    string m_name;
    list* _list;
};
void func(IFile* f1)
{
    IFile *f2 = new Dir("电影");
    IFile *f3 = new Dir("游戏");
    IFile *f4 = new Dir("哈利波特");
    IFile *f5 = new Dir("学习");


    IFile *w1 = new File("哈利波特1");
    IFile *w2 = new File("哈利波特3");
    IFile *w3 = new File("大黄蜂.mp4");
    IFile *w4 = new File("疯狂的外星人.mp4");
    IFile *w5 = new File("DOTA2.exe");
    IFile *w6 = new File("剑指offer.pdf");


    f1->add(f2);
    f1->add(f3);
    f1->add(f5);

    f2->add(f4);
    f2->add(w3);
    f2->add(w4);
    f3->add(w5);
}
bool mycompare(IFile* left,IFile* right)
{
    return left->getname()getname();
}

void show(IFile *file,int level)
{
    for(int i=0;ishow();
    list* m_list = file->Getchild();
    if(m_list!=NULL)
    {
        m_list->sort(mycompare);
        list::iterator it = m_list->begin();
        while(it!=m_list->end())
        {
            show(*it,level+1);
            ++it;
        }
    }


}

int main()
{
    IFile *f1 = new Dir("D盘");
    func(f1);
    show(f1,0);
    return 0;
}

你可能感兴趣的:(学习C)