java design – which class stores application-wide object?

I have a Server object that is obtained when the application runs, and I need to keep it for the duration of the application. It is just a model object with an id, and hostname.

From the standpoint of good software design and separation of concerns, where would the object be stored and how would it be accessed?

Let me provide some code.

public interface ServerDao{
    Server findByHost(String host);
}

This is how I obtain the object from a DAO. The implementation is irrelevant.

Now let’s say I want to have a method called getCurrentServer which can be called across the entire application, and it obtains the Server object that belongs to the machine that is running the application (based on hostname).

public Server getCurrentServer() {
        ServerDao dao = // some way to get it
        try {
            return dao.findByHost(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            LOGGER.error("Host not found", e);
        }
        return null;
    }

It’s probably a bad idea to place it into the ServerDao class. It’s probably a bad idea to place it into my Application class.

Where would I place such a method? Should I create a ServerContext class, with a singleton of the Server? What is the standard approach?

Thanks.

You have a CurrentServer. The important thing to realize is that CurrentServer is a selection, and that selection is updated by one and shared across the entire application state.

If you want this persisted between runs of the application, you probably need a CurrentServer DAO, with explicit storage. Then each of your components can select the CurrentServer and possibly update it.

This means you need a primary key in the database that can only have one value. Primary Key column current with a data type of Boolean, where the value others select is True should do the trick.

Now you can have multiple instances of the data, but the instances might grow stale. This is easier to account for (and more scaleable) than the kind of contention a Singleton approach will eventually cause.

public CurrentServer getCurrentServer() {
    CurrentServerDao dao = new CurrentServerDaoImpl(new DefaultDatabaseService());
    try {
        return dao.findByCurrent(Boolean.TRUE);
    } catch (UnknownHostException e) {
        LOGGER.error("Host not found", e);
    }
    return null;
}