Search code examples
javaobserver-pattern

Java observer pattern how to handle lots of events


I'm working on a application that has a client and a server. When the client receives a packet it needs to notify whatever screen object needs what packet (for instance the login screen is only interested in packets about logging in).

Currently I have the system set up so all screen objects are notified of any in coming packets. Then each screen checks to see if the packet that came through applies to its self.

I was wondering if anyone knows any way so instead of every screen object listening out for every packet, the network listener just sends what packet the screen is listening for. (that way I don't have to have a 100 if statements to check if the packet coming through is a,b,c,d,e,f). I could do this by implementing a new event for each packet but that could get messy quickly.

any help on the matter would be amazing.


Solution

  • This could be a solution for your problem. Create an interface Packet:

    public interface Packet {
      public void callListener();
    }
    

    For each packet create a class that implements Packet. For example, to manage the login packets you can create a LoginPacket class:

    public class LoginPacket implements Packet{
      public void callListener() {
        ListenerLogin.notify(this);
                //you can add additional Listeners
    
      } 
    }
    

    In the main class Reader when read a packet call the specific listener(s):

    public class Reader{
      public void parse(Packet p) {
       p.callListener();
    }
    }
    

    In this way, you don't need any if/else statement in the parse method.