I am currently trying to write a Parser system for my project. There are different type of files to be parsed (file1, file2, file3):
file1 -> AData // stored in AData class using AParser class's parsing logic
file2 -> BData // stored in BData class using BParser class's parsing logic
file3 -> CData // stored in CData class using BParser class's parsing logic
Files could be binary or txt. Different files require different logic for parsing because of the way file are written.
I have used a factory pattern for this purpose. The Base class is Parser which is an abstract class.
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
// Base class
template <class T>
class Parser {
public:
virtual void DoParsing(T&, std::ifstream& fs) = 0;
};
// Base class for data
struct Data {};
//////
struct AData : Data {
int data;
};
class AParser final : public Parser<AData> {
public:
void DoParsing(AData& data, std::ifstream& fs) {
// implementation goes here
}
};
///
struct BData : Data {
char* data;
};
class BParser final : public Parser<BData> {
public:
void DoParsing(BData& data, std::ifstream& fs) {
// implementation goes here
}
};
template <class T>
class IParsing {
public:
void action(std::shared_ptr<Parser<T>> p, T d, std::ifstream& fs) {
p->DoParsing(d, fs);
}
};
class FParsing {
public:
FParsing() {}
void HandleParsing(std::string type, Data& d, std::ifstream& fs) {
if (type == "AParsing") {
std::shared_ptr<IParsing<AData>> iparse =
std::make_shared<IParsing<AData>>();
iparse->action(std::make_shared<AParser>(), static_cast<AData&>(d),
fs);
} else if (type == "BParsing") {
// iparse->action(std::make_shared<BParser>(), fs);
std::shared_ptr<IParsing<BData>> iparse =
std::make_shared<IParsing<BData>>();
iparse->action(std::make_shared<BParser>(), static_cast<BData&>(d),
fs);
} else {
std::cout << "Need shape\n";
}
}
private:
};
int main() {
std::ifstream iFile("data.txt");
FParsing fparse;
//AData is passed by ref because
// it will be populated during parsing process
AData ad;
fparse.HandleParsing("AParsing", ad, iFile);
// BData
BData ab;
fparse.HandleParsing("BParsing", ab, iFile);
}
My questions are:
- Do you think this is a right approach for creating a parsing system?
- Is the factory pattern implementation correct?
- I just wanted to make sure I am not making things more complex than it should be.
- Are there other design patterns better than factory pattern for this purpose?