lundi 2 juillet 2018

Is using dictionary good practice to keep same classes?

I need to collect some classes and provide it by request to some parts of program. I have following code:

public interface ISameClass
{
    int Value { get; set; }
    void DoStuff();
}

public class SameClass : ISameClass
{
    int Value { get; set; }
    void DoStuff()
    {
    //Do something
    }
}

public class SameClassProvider
{
        private readonly Dictionary<string, ISameClass> _sameClasses;

        public SameClassProvider(string parentDir)
        {
            _sameClasses = new Dictionary<string, ISameClass>
            {
                { "Type1", new SameClass() },
                { "Type2", new SameClass() },
                { "Type3", new SameClass() }
            };
        }

        public bool AddClass(string type, ISameClass class)
        {
            if (_sameClasses.ContainsKey(type) || class == null)
            {
                return false;
            }

            _nodes.Add(type, class);
            return true;

        }

        public ISameClass GetClass(string type)
        {
            if (_sameClasses.TryGetValue(type, out var someClass))
            {
                return someClass;
            }
        }
}

Is using classes like SameClassProvider is good practice? Or i can refactor this something or replace with correct pattern? Tnx

Aucun commentaire:

Enregistrer un commentaire