Depends on the nature of the data. Is it static? I mean, is it likely to be the same every time the program is run? If so, I'd be tempted to just have it in a properties file which populates a bunch of static fields on some class or other.
If it's dynamic data, that's added to and changed by the running program, you'll want some sort of persistent storage to be involved. Then you're talking something else. I'd steer clear of the singleton "pattern" really, and instead have some sort-of application context, an object that all the other objects that need the data carry a reference to, and can look up the data from as they need it. The context itself can get to it's dependents in a manner of ways, including being injected at startup (very in-vogue at the moment) or, of course, looked up in a singleton heh heh
Without more info, it's hard to say. But using inheritance for this would be a pretty rough abuse of inheritance!
> The data is such as file name which is shared between
> all classes.So if not inheritance - how should i
> implement it?
> Thank u !
As already stated--your question is too vague. "Sharing data" can take many forms and have many purposes.
What does the data represent?
Why does it need to be shared?
Is it all related, or are there many different bunches that aren't related to each other?
Will the classes sharing this data be updating it, or just reading it?
What are the other classes' relationships to the data?
All of the classes may get or set this data .
The Application is Gui application and each tab of it is a class , there is a data which is mutual to all classes such as if im Tab 1 a user will upload a file ,the name of this file suppose to be avalible to all the other Tabs (classes).
How can I slove this ?
Thanks!
> All of the classes may get or set this data .
> The Application is Gui application and each tab of it
> is a class , there is a data which is mutual to all
> classes such as if im Tab 1 a user will upload a file
> ,the name of this file suppose to be avalible to all
> the other Tabs (classes).
> How can I slove this ?
> Thanks!
Use a simple application context. This will be an object that holds the shared data, and all the objects which need to know about the data will carry a reference to this shared instance. Depending on your needs, the class might be as simple as
public class AppContext {
private String filename;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
Or, if you envisage that you'll need to share other arbitrary data, it could wrap a hash map for you. But the key aspect is that there is a class which the other objects in your application will all carry (or can access) the same instance of to get at the data. One way of ensuring this would be to have the classes which depend on this data to take the application context as a constructor argument, and have the shared instance passed to them all