All examples which I found in general base on enumeration which provides to return the proper class. I need something which reacts in general on type of class and also is controlling constructors of new object by giving to it new parameters with each call.
Is it still factory method? Is it good solution? Can I play with design patterns in such way? Maybe there is better solution to provide?
using System;
namespace ConsoleApplication1
{
public abstract class Strategy
{
protected int Init;
private static int _initA = 3;
private static int _initB = 42;
public static Strategy StrategyFactory(Strategy strategyType)
{
var tempStrategyA = strategyType as StrategyA;
if (tempStrategyA != null)
{
_initA++;
return new StrategyA(_initA);
}
var tempStrategyB = strategyType as StrategyB;
if (tempStrategyB != null)
{
_initB = _initA * 2;
return new StrategyB(_initB);
}
throw new ArgumentException();
}
}
public class StrategyA : Strategy
{
public StrategyA(int init)
{
Init = init*2;
}
}
public class StrategyB : Strategy
{
public StrategyB(int init)
{
Init = init*3;
}
}
}
To me what it looks like is you actually want to have a different factory for each strategy. Factories are good if you want to either manage the lifetime of the objects the factory creates, or to manage dependencies / arguments for the construction of the various types.
Definition of strategy factories
interface IStrategyFactory
{
public Strategy Create(int value);
}
class StrategyAFactory : IStrategyFactory
{
public Strategy Create(int value)
{
return new StrategyA(value);
}
}
class StrategyBFactory : IStrategyFactory
{
public Strategy Create(int value)
{
return new StrategyB(value);
}
}
Usage
class MyController : ApiController
{
private IStrategyFactory _factory;
public MyController(IStrategyFactory factory)
{
_factory = factory;
}
public HttpResponseMessage Get(int value)
{
// here we don't care what exact strategy is used, this is good!
var strategy = _factory.Create(value);
var newValue = strategy.Calculate();
return new HttpResponseMessage(newValue);
}
}