I have a number of classes that contain the ability to be written to either a CSV or XML file. To accomplish this, I pass in an instance of a StreamWriter or XmlWriter to ToCsv or ToXml methods.
public class HandFeed : JobItem
{
// Snip
public override void ToCsv(StreamWriter writer)
{
if (writer != null)
{
writer.WriteLine(JobItemsStrings.Job_HandFeed);
writer.WriteLine(JobItemsStrings.Job_Total + SEPARATOR_CHAR + this.Total.ToString());
}
}
public override void ToXml(XmlWriter writer)
{
if (writer != null)
{
writer.WriteStartElement("handfeed");
writer.WriteElementString("total", this.Total.ToString());
writer.WriteEndElement();
}
}
}
Now I am looking to provide suport for JSON too, and if I carry on in the same way, this would mean adding another method to all my classes along the lines of 'ToJson' or similar.
Well, this feels like it is wrong somehow. I am thinking of maybe doing things the other way around and passing instances of the classes to different file writer objec开发者_如何学编程ts instead, but not really sure if this would be the right thing to do either, or even how best to accomplish it.
Perhaps I can pass in an interface and call Write()
? This feels like it would be more correct, but again, how to put this into practice.
So, my questions in a nutshell are:
- Should the classes be 'injected' with writers?
- Should some writers be 'injected' with the classes?
- Stick with the current setup, but create some form of interface instead?
Any advice welcome.
You could write "Writers" that conform to an interface and inject the writers. However this would mean that a given object can only be written to a single format in any single state. This might not be a problem for you, and if it isn't this is a practical approach.
The other option would be to create writers that conform to the interface but leave the objects out of the business of writing themselves out. Instead some caller can setup the writer and pass the object to it. This relates to a question I just answered:
Should classes be able to save and load themselves via XML?
In your case the caller that wishes to write out then can get the "writer" via some factory that is able to resolve the correct writer to use.
I wouldn't stick to your current setup because as you mention, each time a new format is needed, you need to modify your existing code and add methods for that format. Also, you are telling your objects that they should know how to do too much.
I think you need to apply the servant design pattern, you can read about it on this link
精彩评论