I am trying to resolve a circular dependency between two components in my system. The Messenger
component is responsible for sending and receiving messages on a web socket. The Controller
component requires use of the Messenger
component to be able to send messages to connected clients because the Messenger
component knows about the connected sessions.
The Messenger
component has a dependency on the Controller
component to be able notify the controller of incoming messages.
The WebsocketHandler
is a framework interface that I have no control over in this case and calls the appropriate methods on my implementation based on the connected clients.
What architectural changes could I make to resolve this?
interface WebsocketHandler
{
void onConnect(Session session);
void onDisconnect(Session session);
void recieve(Object payload);
}
class Messenger implements WebsocketHandler
{
Controller controller;
Set<WebsocketSession> websocketSessions;
@Override
void onConnect(Session session)
{
sessions.add(session);
}
@Override
void onDisconnect(Session session)
{
sessions.remove(session);
}
@Override
void recieve(Object payload)
{
controller.messageReceived(payload);
}
// requires access to sessions to send messages
void send(Object payload)
{
for (WebsocketSession session : websocketSessions)
{
session.send(payload);
}
}
}
class Controller
{
Messenger messenger;
void messageReceived(Object payload)
{
// do something with payload
}
void notifyClients()
{
messenger.send(...);
}
}