I have something like this:
public class Map
{
class DataHandler
{
private int posX, posY;
// Other attributes
public int GetX() { return posX; }
public int GetY() { return posY; }
// Other functions for handling data (get/set)
}
class FileHandler
{
// Functions for reading/writing setting files
}
DataHandler Data;
FileHandler Files;
public Map()
{
Data = new DataHandler();
Files = new FileHandler();
}
}
Now, when I write a setting file I need to read some variables (non-static) of the DataHandler
class.
For instance, let's suppose I want to get the value of posX
and posY
, using the GetX
and GetY
methods, in order to write them in the file. How can I access the 'Data' instance in Map from the 'Files' instance?
I know that I could pass as parameter, to the function that writes the file, the instance of the DataHandler class, but it's not like I thought it. In my idea, it should read data (posX
and posY
in this case) by itself, since it is inside the same Map
class. Is there a clean way to do this?
EDIT:
I could pass the instance of the Map
class to the FileHandler
constructor, so it has a way to access its parent class and therefore Data, but I understand it's not a good way to solve the problem.
So, there is no problem to change my structure, I understand that there is something wrong in it, otherwise I won't have this problem, but I don't know how to change it. If you have any suggestion feel free to write it.
Just to explain better the context. I have a map, which is composed of various data (x, y, height, width, name, ...), some images which describe it (for example, a RGB image for the terrain height, I've already planned the class to handle images) and some setting files. In one of these files there must be written some of the map data. So, my idea was to have a parent Map class, with the three classes for handling data, images and files inside, but this problem came up so I think it's not a good structure.
If you strongly against changing structure (but it is recommended way) I suggest you refactor DataHandler and FileHandler - implement it as Singleton, so in any line of your code you can access it as via
DataHandler.Instance.GetX()
andFileHandler.Instance.SomeMethod()
.Basic implementation of singleton is:
UPD: My sample is not thread-safe.
No. You will have to pass data back and forth between the
DataHandler
andFileHandler
in yourMap
class, they do not automagically get informed of each other's presence.It would really help if you could explain a bit what everything is supposed to do, as your class names seem to be a bit too generic.