samedi 23 mars 2019

A design pattern for two different "strategies", that do not implement the same interface

I've built some program with ReactJS and SocketIO, that serves as a fully customizable tool for communicating with a socketIO server.

You can register events to listen to, send messages of any type, pass configuration object to the connection, etc.

Now i've decided to add support for native websockets. The problem is, that native web sockets are simpler, and do not implement the same functionality that SocketIO does.

For instance, i have this method in my React container(where all my main logic is concentrated, no Redux):

registerEventToSocket = (instanceId, socket, eventName) => {
      socket.off(eventName);

      socket.on(eventName, (...args) => {           
        const lastArg = args[args.length - 1];
        const isFunction = this.isFunction(lastArg);

        if (isFunction) {
          lastArg();//If a callback was supplied from the server, it is invoked.
          var index = args.indexOf(lastArg);
          if (index > -1) {
            args.splice(index, 1);
          }

        }

        this.addMessageToState(instanceId, eventName, args, false)
      })
    }

This method is called when the user "adds an event" to listen to. In the case of native websockets, there is only one event to listen to, which is "onmessage" event, so this whole functionality is irrelevant.

The app does few more things that would be useless with native sockets, like an option to "listen to all incoming events".

I'm trying to think of some good design pattern, which i could use to create some polymorphism here, to deal both with the SocketIO case, and the native one.

I'm familair with "strategy pattern", which i used a lot, but in my case both "strategies" would implement two different interfaces, which would violate SOLID principles.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire