I have multiple classes whose properties need to be written to a text file. Since each class has different properties each requires a different algorithm to write. I'm trying to use a strategy pattern for this but it doesn't seem to be working out - don't know if this is even the correct pattern to use?
class A
{
void one;
void two;
void three;
}
class B
{
void four;
void five;
void six;
void seven;
}
class C
{
void eight;
void nine;
}
This is where im having trouble with my design, how would I pass the object into the concrete strategy?
class DataParser
{
Object object;
void DataParser(Object object)
{
this.object = object;
parsers.put(new ClassA(), new ClassAParser());
parsers.put(new ClassB(), new ClassBParser());
parsers.put(new ClassC(), new ClassCParser());
}
void writeData()
{
ParserInterface parser = parsers.get(this.object);
/*
* classAParser.setClassA(object);
* classBParser.setClassB(object);
* classCParser.setClassC(object):
*/
parser.write();
}
}
.
interface ParserInterface
{
void write();
void read();
}
.
class ClassAParser()
{
ClassA classA;
void setClassA(ClassA classA)
{
this.classA = classA;
}
void write()
{
PrinterWriter writer = new PrintWriter("ClassA.txt");
writer.printLn(this.classA.getOne() + "|" + this.classA.getTwo() + "|" + this.classA.getThree());
writer.close();
}
void read()
{
}
}
.
class ClassBParser()
{
ClassB classB;
void setClassB (ClassB classB )
{
this.classB = classB ;
}
void write()
{
PrinterWriter writer = new PrintWriter("ClassB.txt");
writer.printLn(this.classB.getFour() + "|" + this.classB.getFive() + "|" + this.classB.getSix() + "|" + this.classB.getSeven());
writer.close();
}
void read()
{
}
}
So then I can just simply do something like this:
class Test()
{
void testClassA()
{
ClassA classA = new ClassA();
classA.setOne("One");
classA.setTwo("Two");
classA.setThree("Three");
DataParser parser = new DataParser(classA);
parser.writeData();
}
}
Then the ClassA.txt should have the following: "one|two|three"