This should be simple but the brain isn't quite caffeine'd up yet this morning.
I have an invoice file (actually dataset, but, whatever). I'm reading it line by line, top down. If the line has an O in the type column, it's the start of a new order, and contains order info, and section heading details. When it contains an S, it has the same heading details for a sub section. The other lines are the details for their respective sections with item number and quantities (Related to headings in O/S lines).
example
O o123 typea typeb typec
1234 3 2 6
2345 1 0 2
S typed typee typef
1634 3 2 6
2645 1 0 2
O o123 typea typeb typec
1234 3 2 6
2345 1 0 2
S typed typee typef
1634 3 2 6
2645 1 0 2
S typed typee typef
1634 3 2 6
2645 1 0 2
I am not struggling with changing type, and handling the开发者_运维问答 state machine aspects of reading the file. What I'm struggling with is the object model.
I initially read the row into a generic line class, then need to convert it to it's proper type... but what's the proper way to lay out these classes? How should my interfaces look so I can write this cleanly. Should there be an abstract class?
If it makes a difference, I'm coding in c# (framework 3.5).
Thanks
You should use some flavor of the Factory Method pattern.
This is usually implemented by having a number of classes deriving from a common base or implementing a common interface -- this depends on the relations between the classes. Let's go with the second option and assume ICommon
. Then, you populate a map of "distinctive values" to instances of Action<ICommon>
.
In your example, we might have:
var map = Dictionary<string, Action<ICommon>()
{
{ "O", () => new Order() },
{ "S", () => new Subsection() },
};
Then, you create the factory method that takes whatever your input is, finds the appropriate action from the map, creates the object and returns it to the caller:
public static ICommon CreateCommon(FileLine line)
{
// assume map is visible
var producer = map[line.Type];
return producer();
}
That's all there is to it. Usually all of this is packaged into a static class, and depending on the particulars of your case the map may be populated with hardcoded data, or automatically by some algorithm (think static
constructor of the class that packages these) or even programmatically by your code before using the factory method.
精彩评论