Mama Tate
Mama Tate

Reputation: 283

return a singleton from generic class

GameControl.GetControl<GameTimeControl>().Days

where

public static class GameControl
{
    public static T GetControl<T>()
    {
        T result = default(T);
        return result;
    }
}

I am fairly new to generics, but what I am trying to do is get a singleton class through the GetControl, but when I try to start the game,the log says that is not an instance of an object.I am not sure can I achieve such a thing with singletons.

Is there a way to access lots of singletons through a generic method?

Ok maybe the question was not clear enough..Let me explain better. I have the singleton classes with the singleton pattern: GameTimeControl, WeatherControl, TemperatureControl etc. I want to access each of them at run time only with one method which i though it can be a generic method.So further to the question what is the best way to access all singletons with one method and if it can - the method to expose their class members and methods.

Upvotes: 2

Views: 414

Answers (2)

Matten
Matten

Reputation: 17631

To expand a little bit on the other suggestions, you'll need to keep a list of the instances you already created and if a new one is requested, you'll need to create an instance:

static Dictionary<Type, object> instances = new Dictionary<Type, object>();
public static T GetControl<T> where T: new() {
  T retVal = default(T);
  if (instances.ContainsKey(typeof(T)))
  {
    retVal = (T)instances[typeof(T)];
  }
  else
  {
    retVal = new T();
    instances.Add(typeof(T), retVal);
  }

  return retVal;
}

Note: this is a very simple version and does not prohibit to make new instances of the T classes. You'll probably make the ctors private and use some kind of fabric method or reflection to create the instances.

Just to show how it could be implemented with a private constructor:

static Dictionary<Type, object> instances = new Dictionary<Type, object>();
public static T GetControl<T> {
  T retVal = default(T);
  if (instances.ContainsKey(typeof(T)))
  {
    retVal = (T)instances[typeof(T)];
  }
  else
  {
    Type t = typeof(T);

    ConstructorInfo ci = t.GetConstructor(
      BindingFlags.Instance | BindingFlags.NonPublic,
      null, paramTypes, null);

    retVal = (T)ci.Invoke(null); // parameterless ctor needed
    instances.Add(typeof(T), retVal);
  }

  return retVal;
}

Upvotes: 1

helb
helb

Reputation: 7773

You may want to return the singleton instances in your GameControl class depending on the type used for T:

public static class GameControl
{
    public static T GetControl<T>()
    {
        if(typeof(T) == typeof(GameTimeControl)
        {
            return GameTimeControl.Instance();
        }
        // TODO: other singletons
        return null;
    }
}

You can design your singltons like normal singletons (e.g. private constructor) and call GameControl.GetControl<T>() like you wanted.

Upvotes: 0

Related Questions