singleton design question

R

Rusty Wright

I have some classes for reading properties files where the properties
are then used for setting up a database connection and an ldap
connection. At the moment I'm not caching the connections and I'm
reopening the connections to the database and ldap every time I need
stuff from them; I'll fix that later. But I don't want to reload the
properties files every time so I've set up the properties to be
static.

There's a common method in the parent class that loads the properties
files, the child classes call it with the name of the file to load.

class Props {
protected Properties loadProps(String file) {
Properties props = new Properties();

try {
InputStream in = this.getClass().getResourceAsStream(file);
props.load(in);
in.close();
}
catch (IOException e) {
e.printStackTrace();

System.exit(1);
}

return(props);
}
}

Here's the child class that loads the database properties. The ldap
one is the same except for the argument to PropsDB

class PropsDB extends Props {
private static Properties props;

private PropsDB(String file) {
props = loadProps(file);
}

public static Properties getProps() {
if (props != null)
return(props);

new PropsDB("db.props");

return(props);
}
}

Since the props field is static, as is getProps() I have to do some
contortions to call loadProps() from the parent, by instantiating. I
get/use the properties as a static call with PropsDB.getProps().

It seems to me that I could avoid this rigmarole of instantiating
PropsDB by getting rid of the child classes and creating 2 methods in
Props; getPropsDB() and getPropsLDAP(), with their corresponding
static fields. Would that way be better than the way I'm doing it
now?
 
M

Malte

Rusty said:
I have some classes for reading properties files where the properties
are then used for setting up a database connection and an ldap
connection. At the moment I'm not caching the connections and I'm
reopening the connections to the database and ldap every time I need
stuff from them; I'll fix that later. But I don't want to reload the
properties files every time so I've set up the properties to be
static.

For a database connection pool I use the following 'template'. You shold
be able to stick the Properties stuff in there as a private field and
create an access method for it. You access the whole thing using
MyClassImpl.getInstance().

public class MyClassImpl implements MyClass
{
private static MyClassImpl instance =
new MyClassImpl();
private MyClassImpl()
{
// whatever
}

public static MyClassImpl getInstance()
{
return instance;
}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top