1
It’s a half-ass question whose answer might be "make the most sense of the code," but it doesn’t hurt to ask.
The pattern Observer suggests that an observer register (via observable.registerObserver(observer)
or observable.addObserver(observer)
, is the same thing) along with the observable to receive events and similarly to slip through a observable.unregisterObserver(observer)
or observable.removeObserver(observer)
).
But in certain situations it may be necessary to inject the observer into the observable, which is less dynamic. I think in the case of an observable class SocketHandler
, encapsulating a Socket
TCP already opened on the server side and encapsulates also a Thread
which is started immediately after a new connection is accepted. In this case there seems to be no opportunity to register the observer; the class SocketHandler
then authenticates through the protocol it implements (which is one of the events that interest the observer, so the observer must already be registered) once the thread is started.
In the example below do not confuse the listeners (Observers) of the class Server
with the class Observer SocketHandler
, who is called commandSender
and is being injected into the class SocketHandler
as quoted in the question.
class Server {
...
private void acceptConnectionsLoop() {
try {
while(true) {
Socket socket = serverSocket.accept(); // bloqueante
SocketHandler socketHandler = new SocketHandler(socket, 20, commandSender);
socketHandler.start();
listeners.forEach((listener) -> listener.onNewHandler(socketHandler));
}
} catch (IOException e) {
stop();
}
}
...
}
The whole point is that a SocketHandler
is part of a list that can receive commands and transmit them to the client that is connected.
So here is the question: it is better to be more "purist" and try somehow to implement an Observer that registers and disconnects or should I choose the less dynamic way of injecting the Observer in the observable?