Search code examples
javaparametersstrategy-pattern

extended Strategy Pattern with Parameters: How to set values


So basically I have different scientific models (algorithms) for calculating a certain value. Each algorithm can have a different set of Parameters to fine-tune the model. These parameters must be changeable by the user. (for now it will be a simple properties file). Language I'm using is Java.

So I tried to follow this publication

http://www.hillside.net/plop/2010/papers/sobajic.pdf

Here a code sample from above pdf, I asssume it is C#:

abstract class Algorithm
{
    public Algorithm()
        { }
    protected Parameter[] parameters;
    public Parameter[] getParameters()
        { return parameters.copy(); }
    public abstract void execute();
}

abstract class Parameter
{
    private string name;
    public string GetName()
        { return name; }
    public Parameter(string name)
        { this.name = name; }
}
class BoolParameter : Parameter
{
    private bool Value;
    public bool GetValue()
        { return Value; }
    public void SetValue(bool value)
        { Value = value; }
    public BoolParameter(string name, bool defaultvalue)
        : base(name)
    {
    Value = defaultvalue;
    }
}
class IntParameter : Parameter
{
private int min;
    private int max;
    private int Value;
    public int GetValue()
        { return Value; }
    public void SetValue(int value)
    {
        if (value < min)
        throw new ArgumentOutOfRange(GetName() + " can’t be less than " + min);
        if (value > max)
        throw new ArgumentOutOfRange(GetName() + " can’t be greater than " + max);
        Value = value;
    }
    public IntParameter(string name, int min, int max, int defaultvalue) : base(name)
    {
        this.min = min;
        this.max = max;
        Value = defaultvalue;
    }
}

How do i set the Parameters values? Assume the concrete algorithm returns an array or list of 2 Parameters, one an IntegerParameter, the other a StringParameter. However the Parameter interface in above explained pattern has no setValue method and hence how can the Client set the parameters value and know its type?


Solution

  • I would treat all parameter as an int or double even if there is only two possible values e.g. use 0 and 1 instead of true and false.

    Your algo needs a collection a parameters which can altered so it can produce a result.