samedi 17 septembre 2016

Configuration Class Design Pattern

I would like to create a configuration class that the main objects of my code will use to operate. The issue I am having is that some of the variables that I would like to set depend on other variables within the same class. To illustrate:

interface IStringParser<T>
{
    T Parse(string data);
}

class BaseIntParser : IStringParser<int>
{
    public int Parse(string data) { return int.Parse(data); }
}

class RegexIntParser : IStringParser<int>
{   
    Regex _regex;
    IStringParser<int> _baseParser;

    public RegexParser(IStringParser<int> baseParser, pattern)
    {
        _regex = new Regex(pattern);
        _baseParser = baseParser;
    }

    public int Parse(string data)
    {
        var m = _regex.Match(data);
        return _baseParser.Parse(m.Groups[1].Value);
    }
}

class ConfigurationTemplate
{
    public IStringParser<int> BaseIntParser = new BaseIntParser();
    public IStringParser<int> RegexIntParser = new RegexIntParser(baseIntParser, "pattern");
}

Are there any elegant workarounds that would allow me the functionality that I am attempting here?

Aucun commentaire:

Enregistrer un commentaire