jeudi 20 octobre 2016

How to implement a factory that automatically finds a strategy

I've asked myself this question and I'm still not done thinking about this.

What I am thinking about

When you have a strategy pattern, a lot of implementations also use a factory pattern to retrieve a specific strategy. Most factory examples on the internet make use of a switch or if statement. This works perfectly when you do not often change or add strategies. But what if the factory is used to dynamically find a strategy and the strategies are changed and added often. Then this is a full time job for the programmer. Now I have a situation where I just want to add a new strategy without having to change the factory. In other words how do you implement the factory pattern so it dynamically searches for a strategy. And how can I list all available strategies.

The problem

When I look for this on the internet I can't find a good proper solution. I am thinking about using a reflection library to do this but it is not recommended to use reflection everywhere I look. So how to implement a dynamic factory. Or is there an other pattern for this purpose?

Example

The strategies: enter image description here

The factory:

public enum StrategyName { ImplementedStrategy1, ImplementedStrategy2, ImplementedStrategy3 };

public class StrategyFactory
{
    public static Sniffer getInstance(StrategyName choice) {

        Strategy strategy = null;

        switch (choice) {
            case StrategyName.ImplementedStrategy1:
                strategy = new ImplementedStrategy1();
                break;
            case StrategyName.ImplementedStrategy2:
                strategy = new ImplementedStrategy2();
                break;
            case StrategyName.ImplementedStrategy3:
                strategy = new ImplementedStrategy3();
                break;
        }

        return strategy;
    }
}

Now how can I make this dynamic? Or why shouldn't I?

Aucun commentaire:

Enregistrer un commentaire