ro-E
ro-E

Reputation: 299

creating a template method in a static method

I created a class InputBox that only has one method, which is static:
Public static Show(string i_Prompt)

this method creates an InputBoxForm and gives the form a method for this property:
public Predicate<char> isKeyValid { get; set; }
which runs in here:

    private void textBoxInput_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (isKeyValid != null)
        {
            e.Handled = !isKeyValid(e.KeyChar);
        }
    }

the idea is that a developer will derive my class and create he's own logic on how to deal with getting characters from the user.

this implementation of the static Show method is:

    public static string Show(string i_Prompt)
    {
        string input = string.Empty;

        using (InputBoxForm form = new InputBoxForm(i_Prompt))
        {
            form.isKeyValid = s_Instance.keyValidationLogic;
            if (form.ShowDialog() == DialogResult.OK)
            {
                input = form.Input;
            }
        }

        return input;
    }

the template is keyValidationLogic. (which return true for all the keys in the base InputBox)
the problem, as you can see that i cannot overwrite a static method.
how would I implement a template method in a static method?

I have to create an instance of the Input Box, but I want to use the derived class instance

the class InputBox is not static. i want it to be derived, so developers will be able to customize the logic of the input box.

thanks

Upvotes: 0

Views: 94

Answers (1)

JLRishe
JLRishe

Reputation: 101662

I'm not sure your approach is the best way to to about this, but you should be able to solve your issue in the following way.

You can do this with ordinary inheritance:

class InputBox
{
    protected virtual bool ValidateKey(char key)
    {
        // Allow anything
        return true;
    }

    public string Show(string i_Prompt)
    {
        using (InputBoxForm form = new InputBoxForm(i_Prompt))
        {
            form.isKeyValid = this.ValidateKey;
            if (form.ShowDialog() == DialogResult.OK)
            {
                return form.Input;
            }
        }

        return string.Empty;
    } 
}

class DigitInputBox : InputBox
{
    protected override bool ValidateKey(char key)
    {
        return key >= '0' && key <= '9';
    }
}

To use:

(new MyCustomizedInputBox()).Show("Numbers only, please!");

Upvotes: 2

Related Questions