I'm trying to practice using composite pattern and I made a basic scenario of file/folder example. but I found a problem, let first describe what I already implemented, I have as input a vector of string, this vector of string contains the names of different folders and files in a hierarchy of a folder, the file name starts with a capital letter and the folder name is lower case.
I need to deserialize them into IComposite that contains the hierarchy of these files and folder in the correct order, this is my first implementation.
class IComposite
{
public:
virtual void display() = 0;
};
class File : public IComposite
{
public:
File(std::string name);
void display() override;
private:
std::string m_name;
};
class Folder : public IComposite
{
public:
Folder(std::string name);
Folder(std::string name, std::vector<IComposite *> comp);
void display() override;
void addValue(IComposite* value)
{
m_comp.push_back(value);
}
private:
std::string m_name;
std::vector<IComposite*> m_comp;
};
IComposite* deserialization(std::vector<std::string> values)
{
for (; index<values.size(); ++index)
{
if (isCapital(values[index]))
{
return new File(values[index]);
}
else
{
Folder* f = new Folder(values[index]);
f->addValue(deserialize(values, ++index));
}
}
}
Since we are using a "recursive call", if we have a folder that contains one folder and one file, when we deserialize this data the file will be pushed first in the std::vector<IComposite*> m_comp in the composite class, so the order will be not respected and this is the problem.
How we can deserialize the data in the correct order ? if we have a file, folder, file in one folder I need them to be in the exact order in the final result.
Ps : There are some problems in the implementation of the deserialization function but I hope you get the idea.
Aucun commentaire:
Enregistrer un commentaire