My question is whether there is a similar pattern to Observer that does not imply a state change in the observed object. The following is a concrete example:
I have a ConnectionFactory
class which is responsible for creating JDBC database connections. Now I have the need to do something with every connection right after it has been created (specifically, I need to set a user-defined variable in the MySQL session) but I don't want to do it in the ConnectionFactory
class since I feel this is something that goes beyond its responsibilities.
I have considered making ConnectionFactory
extend java.util.Observable
and having an Observer
class that will be notified every time a connection is created. However it seems that this approach is incorrect, since the Observer pattern implies that the observed object is being observed for state changes, but the state of ConnectionFactory does not change at all when a connection is created.
As you can see, I have to go around this issue by simulating a state change before calling notifyObservers()
(otherwise the observers will not be notified) and synchronizing those two statements in order to make sure that the "state changed" flag set in the first statement is still active when the second statement is executed. This kind of workaround just increases my suspicion that I have taken the wrong approach.
public class ConnectionFactory extends java.util.Observable {
public static final ConnectionFactory INSTANCE = new ConnectionFactory();
private ConnectionFactory(){};
public Connection makeConnection(){
Connection connection = null;
// ... obtain the connection ...
synchronized(this) {
this.setChanged();
this.notifyObservers(connection);
}
return connection;
}
}
public class Foo implements java.util.Observer {
@Override
public void update(Observable o, Object arg) {
Connection con = (Connection)arg;
// ... set MySQL user-defined variables ...
}
}
// Somewhere in initialization code...
ConnectionFactory.INSTANCE.addObserver(new Foo());
So there is an object that I want to observe, there is a class that must do something when the observed object fires certain events, but those events are not state changes. If the Observer pattern is not applicable, then what would be a correct approach?