我应该在这里使用工厂吗
我有一个简单的 ExcelStringBuilder 类。它用于构建可以导出到 Excel 的字符串。现在我还需要构建一个 CSV 字符串。
我发现实现这两个类的唯一区别是构建字符串时使用的分隔符。对于 Excel,它是“\t”制表符,对于 CSV,它是“,”逗号。
我的想法是将分隔符作为参数传递给 ExcelStringBuilder 类构造函数。这是一个正确的决定还是我应该采用工厂模式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要过度设计它。我只是稍微重构现有的类:
ExportStringBuilder
的内容,ToString()
函数的参数您知道有一些很棒的免费库可用于此,是吗?例如,请参阅这个问题
Don't overdesign it. I would just refactor the existing class slightly:
ExportStringBuilder
ToString()
functionYou are aware that there are some great free libraries available for this, are you? E.g. see this question
如果唯一区别是分隔符,我只会传递该分隔符。其他一切都太过分了。
如果存在更多差异,我将创建一个返回
IStringBuilder
的StringBuilderFactory
。ExcelStringBuilder
和CsvStringBuilder
都将实现该接口。您可以向工厂传递一个参数,告诉工厂您需要 Excel 字符串生成器还是 CSV 字符串生成器,然后它会返回正确的字符串生成器。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 aIStringBuilder
.ExcelStringBuilder
andCsvStringBuilder
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.如果您计划使用工厂,则可以将模板模式与工厂一起使用或单独使用。由于算法的大部分内容除了一个步骤外将保持不变,将来您可能还会有其他步骤(例如新的分隔符),
这是一种使用模板模式的方法。您可以使用“Getter”代替GetDelimiter()。
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().