Question

I have this class:

public static class GameControl
{
   public static DNControl GetDayNightControl()
   {
      return DNControl.Instance;
   }

   public static MapHandler GetMapHandler()
   {
      return MapHandler.Instance;
   }

   public static TemperatureControl GetTemperatureControl()
   {
      return TemperatureControl.Instance;
   }
}

where all of the return types are Singletons.Can any of you guys can give me an idea how can i return any of them with one single method?

Was it helpful?

Solution

Create a wrapper class and return that instead.

public class WrapperClass
{
    public DNControl DayNightControl {get; internal set;}
    public MapHandler MapHandler {get; internal set;}
    public TemperatureControl TemperatureControl {get; internal set;}
}

public static class GameControl
{
    public static WrapperClass GetEverything()
    {
        var wrapper = new WrapperClass();

        wrapper.DayNightControl = DNControl.Instance;
        wrapper.MapHandler = MapHandler.Instance;
        wrapper.TemperatureControl = TemperatureControl.Instance;

        return wrapper;
    }

    // if that's still pertinent you may keep your individual methods too
}

I should mention though: I really do not see the point of keeping those together to begin with. There may be a larger picture I'm not seeing here but it seems to me that your actual way of simply being able to call your individual singletons from a static class is fine as it is. You may benefit from giving more details on the added value you expect out of this.

OTHER TIPS

You could possibly use generics, e.g.

public static T GetControl<T>()
{
    // determine what type to return based on T, and return it
}

I've not tried it out, but off the top of my head, I think something like that should work.

You can try something like this with reflection

public static class GameControl
{

    public static T GetControl<T>()
    {
        return (T)typeof(T).GetProperty("Instance").GetValue(null);
    }

}

Not clear what you're asking, but one way to return all in one method call would be

public static class GameControl
{

    public static void GetSingletons(out DNControl dnControl, out MapHandler mapHandler, out TemperatureControl tc)
    {
        dnControl = DNControl.Instance;
        mapHandler = MapHandler.Instance;
        tc = TemperatureControl.Instance;
        return;
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top