discussing my first try of a custom listener

i want to realize a messaging system over a custom-created listener model
to use only the very basics of a listener pattern, i want to create them right off from zero point, without using component listeners/ action listener

so heres my first try :


public interface MyListener
{
     public void notifyit(Object e);
}


class MrMoo 
{
      MyListener listener;
      
      public MyListener getListener()
      {
            return listener;
      }
      
      public void addListener(MyListener l)
      {
            if(l!=null) listener = l;
      }
      
      public void removeListener()
      {
            listener = null;
      }
      
      public void doit()
      {
            listener.notifyit(this);
      }
      
}



public class ListenerTest
{
      
      public static void main(String args[])
      {
            MrMoo m = new MrMoo();
            
            MyListener l = new MyListener() 
            { 
                  public void notifyit(Object e)  
                        {
                             System.out.println("!!!");
                        }
            };
            
            m.addListener(l);
            m.doit();
      }
      
}

i need some response if im on the right way, if there could be done something better etc

Looks ok, addListener() kinda implies the possibility of multiple listeners though. So either keep a list of the listeners and notify each one when required or change the method to setListener(). If you leave it as it you might want to null check the listener before doing the notification.

Looks good tho,

Kev

If you keep with a single listener then you will want the ‘addListener’ method to return status if the listener was already set… as it is you silently fail to change the listener to what is requested if there already is one.

Generally you have a list of listeners though.

…but if you do want to have a single listener, change the addListener method to setListener, and have it either silently override any currently set listener or throw an exception if a second call is made. Preferably the former.

Edit: Oh, and then you don’t need the removeListener method, as setListener(null) would be the best way to do it.

very nice, thx for the answers. i hope i have now the ‘permission’ to use it as official communication system for my game objects… =)

For the single listener case, rather than throw an exception if there is a current listener… have it return the current listener. Much more robust that way.