try using applicating scope variables.
In UR servlet:
ServletContext application = getServletConfig().getServletContext();
String connection = "URL";
application.setAttribute("appilcation_level_variable", connection );
RETRIEVING:
String conn =
(String)application.getAttribute ("appilcation_level_variable");
Hope this helps!
-M
It depends on what the "something" is IMHO.
For configuration type objects (things that everybody needs access to, but there's really need for only one instance of the data), I like to use the Singleton pattern.
For things that are expensive to use (like database connections) use a Pool or Cache which uses the Factory pattern to fetch instances of the object for use.
I like to have something like Configurator singleton object with public static Something getSomething() methods etc. It is instantiated at the startup time and is available all across the application.
On resources which are expensive to create (db connections etc) you might find Factory pattern useful: cache the connections and let Factory decide wether to return newly created COnnection or a cached one. In that case you'll have something like Factory.getInstance().getConnection() where getInstance() is public static, and getConnection() is instance level method.
I agree, Singleton is the way to go. Here's an example:
public class MyClass {
private static MyClass instance = null;
// notice that the constructor is private
private MyClass() {
}
public static void getInstance() {
if(instance == null) {
instance = new MyClass();
}
return instance;
}
}
// client code
MyClass reference = MyClass.getInstance();
Since the getInstance method is static, it's accessible from anywhere. You can also choose to derive this class and return an instance of a derived class later, with a modified implementation, without changing the client interface.
Dave
Your getInstance() is not thread safe. You could add a static initializer that sets the instance variable when the class is loaded. Then getInstance() can simply return the variable without doing a null check. Of course, if you need to free the instance for some reason, an alternative approach is needed.