Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What pattern to use in this case (interface implementation)

I have a dataset that can be created by a few ways, one of them is by parsing some text, the other way is from a CSV format, the third way is by importing it from a database.

Currently, this is the interface:

 public interface IMyDataMaker
 {
       public MyDataSet MakeData();
 }

and this is the text parser class:

 public class MyDataSetTextParser : IMyDataMaker
 {
       private readonly string textToParse;
       public MyDataSetTextParser(string text)
       {
            textToParse = text;
       }

       public MyDataSet MakeDate()
       {
            // parse the text and return the dataset
       }
 }

the csv parser is closer to the text parser, this is the database class:

 public class DbMyDataSetMaker : IMyDataMaker
 {
       private readonly SqlConnection connection;
       public DbMyDataSetMaker(SqlConnection sqlConn)
       {
            connection = sqlConn;
       }

       public MyDataSet MakeDate()
       {
            // connect to the db and make the dataset
       }
 }

Is this the correct pattern to use in this case?

like image 631
Nean Der Thal Avatar asked Mar 12 '23 09:03

Nean Der Thal


2 Answers

I think this is really good. It's the classic Strategy implementation.

You can now chose the real implementation by dependency injection or creation an method to receive one instance of the interface that you need.

like image 141
Lair Jr Avatar answered Apr 24 '23 23:04

Lair Jr


Yep, that's absolutely the right way to do it. Use constructors to separate out the connection info for each subtype, and end up with a common 'read' method, just as you've done.

like image 21
Steve Cooper Avatar answered Apr 25 '23 01:04

Steve Cooper