Global Variable Access Solution Ideas

I have an initialization class that preloads content into a variable (maybe a list or an array). There will only be one instance of this initialization class, but there will be many classes that need to access the preloaded content.

The problem is not that a lot of them are related and none of them extend my initialization class. I thought about this a bit and decided to use a static method and variable for this use. So something like this ...

public class InitClass
{
     static List PreloadedContent;

     static ModelData GetContent(String ContentName)
     {
          //return the preloaded content that matches given name
     }
}

      

The preloaded content may shrink or enlarge at some time depending on the situation that may be required. I've run into situations where something like this was the only decent search for a solution; I think this is an ugly solution.

Note. I am unable to load data into the class it needs when instantiated for various reasons. Most of them are reasons that I don't know about yet, but, most likely, I can think of. Some classes will be loaded / unloaded depending on the rendering of the scene and my InitClass will not handle the creation of these objects most of the time.

Can anyone give me a better solution?

+1


source to share


2 answers


what you are doing is called singleton . here are some previous discussions on this:



+1


source


To avoid static / global scope you can use some kind of registry class. This means that you have one class that you initialize when you run your program. This class contains links to all other classes that need to be accessed globally. Now you are passing an initialized instance of your registry class to all instances of your application. It's not very cute, but it's the best for me. With static and global variables, I've always had problems when testing or debugging code.



Another approach is to use Singleton. Since they also just contain a static instance, I wouldn't like them.

0


source







All Articles