vendredi 19 juin 2015

Is this use of reflection in state pattern bad practice?

In some of the codebase I'm working on I see a few lot of implementations of state pattern (at least I think its state pattern) that use reflection in the following ways.

In order to store the string version of the type of mode (state):

    public static readonly string login_mode = (new LoginMode()).GetType().ToString();
    public static readonly string config_mode = (new ConfigMode()).GetType().ToString();
    public static readonly string lock_mode = (new LockMode()).GetType().ToString();

and used with a method to switch modes like so:

    private void setMode(string modeName) 
    {
        Mode mode = (Mode)Reflection.getInstance (modeName);
        if (mode != null) {
            setMode (mode);
        }
    }

    public static object getInstance(string classname)
    {
        Type t = Type.GetType(classname); 
        if (t == null) 
        {
            App.Log ("Error: Class not found: " + classname);
            return null;
        }
        return  Activator.CreateInstance(t);  
    }

I think this way is somewhat readable at least, so it isn't terrible in that regard. I've never seen it before (I'm a pretty junior developer, particularly in C#), though, so I want to make sure I'm not learning bad practices from my peers.

Thank you in advance! Dob Jenkins

Aucun commentaire:

Enregistrer un commentaire