How to avoid using this in a contructor

Posted by Paralife on Stack Overflow See other posts from Stack Overflow or by Paralife
Published on 2010-03-23T19:39:00Z Indexed on 2010/03/23 19:43 UTC
Read the original article Hit count: 451

Filed under:
|

I have this situation:

interface MessageListener
{
   void onMessageReceipt(Message message);
}

class MessageReceiver
{
  MessageListener listener;
  public MessageReceiver(MessageListener listener, other arguments...)
  {
     this.listener = listener;
  }

  loop()
  {
    Message message = nextMessage();
    listener.onMessageReceipt(message);
  }
}

and I want to avoid the following pattern: (Using the this in the Client constructor)

class Client implements MessageListener
{
   MessageReceiver receiver;
   MessageSender sender;

  public Client(...)
  {
    receiver = new MessageReceiver(this, other arguments...);
    sender = new Sender(...);
  }
  .
  .
  .
  @Override
  public void onMessageReceipt(Message message)
  {
     if(Message.isGood())
       sender.send("Congrtulations");
     else
       sender.send("Boooooooo");
  }
}

The reason why i need the above functionality is because i want to call the sender inside the onMessageReceipt() function, for example to send a reply. But I dont want to pass the sender into a listener, so the only way I can think of is containing the sender in a class that implements the listener, hence the above resulting Client implementation. Is there a way to achive this without the use of 'this' in the constructor? It feels bizare and i dont like it, since i am passing myself to an object(MessageReceiver) before I am fully constructed. On the other hand, the MessageReceiver is not passed from outside, it is constructed inside, but does this 'purifies' the bizarre pattern? I am seeking for an alternative or an assurance of some kind that this is safe, or situations on which it might backfire on me.

© Stack Overflow or respective owner

Related posts about java

Related posts about design-patterns