1

In my project I have different types of entities.
I get the data for these entities in text files from a 3rd party.
I've written a class to read and parse these text files, using the strategy pattern.
The method in this class must return different entity types so I've made the entire class generic - something like this:

public class Parser<T>
{
    public IStrategy<T> strategy { get;set;}

    public IEnumerable<T> LoadFromFile()
    { 
        // implementation details, not interesting
    }
}

But the problem is that now I need a new instance of Parser for every entity I load, so I changed my initial implementation into this:

public class Parser
{
    public IEnumerable<T> LoadFromFile(IStrategy<T> strategy)
    {
        // implementation details, not interesting
    }
}

So, is this still considered as an implementation of the strategy pattern?

If not, is there any way I could return IEnumerable<T> without having to specify what type T actually is anywhere but in the IStrategy<T>?

  • 2
    Why would it not? You should edit in your concerns so the answers can be tailored to what you actually want to know, otherwise, you're just going to receive a yes/no answer, which is not very interesting. – Vincent Savard Feb 13 '18 at 16:49
  • It's more a question out of curiosity then anything else. I like this solution and don't think I'll change that, I'm just wondering if it's still considered an implementation of the strategy design pattern. – Zohar Peled Feb 13 '18 at 16:50
  • If the strategy changes during the lifetime of the Parser object then it is more of a State Pattern. – A Bittersweet Life Feb 13 '18 at 16:59
  • "But the problem is that now I need a new instance of Parser for every entity I load" Why are you concerned about this? – Erik Eidt Feb 13 '18 at 17:01
  • @ABittersweetLife not unless it's the IStrategy object that sets the next state (strategy), which is obviously impossible in the second implementation. Also, do you have a source for the claim that a strategy must not be changed during the object's lifetime? I've never heard of that. – doubleYou Feb 13 '18 at 17:05
1

Sir, you are still using Strategy pattern in less explicit way. However your code after change does not fully reflect that. You'd have to present the IStrategy interface fot completeness.

However the main line of my thought is rather so: patterns are not blueprints, they are rather intellectual scaffold that more it is modified for concrete use the better it is understood and grasped.

  • Thanks. The IStrategy interface only exposes a few properties such as file name to parse etc', and a method for parsing a single instance of T from a row in the text file. – Zohar Peled Feb 14 '18 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.