How to implement a factory that automatically finds a strategy

I asked myself this question, and I still did not think about it.

What i think about

When you have a strategy template, many implementations also use the factory template to retrieve a specific strategy. Most factory examples on the Internet use a switch or if statement. This works great when you don’t often change or add strategies. But what if the factory is used to dynamically search for strategies, and strategies change and are often added. 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 changing the factory. In other words, how do you implement a factory template so that it dynamically searches for a strategy. And how can I list all the strategies available.

Problem

When I search this on the Internet, I cannot find a good right solution. I am thinking about using a reflection library for this, but it is not recommended to use reflection in everything that I look at. So how to implement a dynamic factory. Or is there another template for this purpose?

Example

Strategies: enter image description here

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?

+4
source share
2 answers

Your contract ImplementedStrategyhas a method IsGoodMatch(params). Then you simply iterate over your collection of strategies, calling IsGoodMatchon each of them until you get one (or many) results, and then use this strategy (s).

+1
source

I'm not sure if this will help, but here is what I think. You

public class ImplementedStrategy1 : Strategy
{

}

public class ImplementedStrategy2 : Strategy
{

}

...

[StrategyName (StrategyName.EnumValue)]. https://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx

,

[StrategyName(StrategyName.EnumValue1)].
public class ImplementedStrategy1 : Strategy
{

}

[StrategyName(StrategyName.EnumValue2)].
public class ImplementedStrategy2 : Strategy
{

}

Sniffer getInstance ( StrategyName) , , , , , .

.

, , .

, .

+1

Source: https://habr.com/ru/post/1658338/


All Articles