gordanvij
gordanvij

Reputation: 1080

Should I use a factory here

I have a simple class ExcelStringBuilder. Its used to build a string that can be exported to Excel. Now I need to build a CSV string also.

The only difference that I see for implementing both of these classes is the delimiter that is to be used while building the string. For Excel it would be "\t" tab character and CSV its "," comma.

What I think is to pass the delimiter as a parameter to the ExcelStringBuilder class constructor. Will that be a right decision or should I go for factory pattern?

Upvotes: 1

Views: 184

Answers (3)

Sandeep G B
Sandeep G B

Reputation: 4015

If you are planning to use a factory, you can use the template pattern along with Factory or independently. As most part of algorithm will remain same except one step and in future you may have additional steps as well (like new delimiters)

Here is one approach using Template pattern. You can use "Getter" instead of GetDelimiter().

class abstract StringBuilder
{
  public virtual string GetDelimiter();
  public string BuildString(string inputString)
  {
     // Your Code goes here...
     GetDelimiter(); // Code to introduce the delimiter
     // Some more of your code
  }
}

class ExcelStringBuilder : StringBuilder
{
 public override string GetDelimiter()
 {
   return "\t";
 }
}

class CsvStringBuilder : StringBuilder
{
 public override string GetDelimiter()
 {
   return ",";
 }
}

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174289

If the only difference is the delimiter, I would just pass that delimiter in. Everything else is overkill.

If there are more differences, I would create a StringBuilderFactory that returns a IStringBuilder. ExcelStringBuilder and CsvStringBuilder would both implement that interface. You would pass a parameter to the factory that tells the factory whether you want a Excel string builder or a CSV string builder and it returns the correct one.

Upvotes: 1

jeroenh
jeroenh

Reputation: 26772

Don't overdesign it. I would just refactor the existing class slightly:

  • rename it to something like ExportStringBuilder
  • pass the delimiter in the constructor, or as an argument of the ToString() function

You are aware that there are some great free libraries available for this, are you? E.g. see this question

Upvotes: 3

Related Questions