I am writing a program which will manipulate certain objects, let’s call them “Words”. Each word is an instance of one of several classes. There can be lots and lots of these at a time.
Each of these Word objects needs access to a dictionary, stored in an XML file. I don’t feel like each Word object should be loading the XML file separately. The Word objects should be able to access some global pool of program data.
What’s the best way to deal with this? Should I have a class called ProgramData which contains the XML document and gets passed to every Word object when they are created? This won’t cause multiple instances of the XML file to be loaded into memory, will it? Can I do what I want to do without passing ProgramData to every new object?
You should load the XML file into one instance of
ProgramData, and then pass that instance into eachWordinstance (maybe in the constructor). You could also make a static property in theWordclass that you set before you start instantiatingWords, but be sure to uselocking for thread safety.Your alternative is the Singleton pattern, but trust me, you don’t want to go down that road.
Edit: Just to be clearer, this is the first option (the one I’d use):