I’ve created a generic ‘SocketServer’ class in java which takes the following arguments:
String address, int port, Class socketProtocol, String encryptionType, int backlogSize
Basically, I want other developers to be able to instance this class in their projects and set some simple options for encryption, backlog, address, port.. at which point they have to design the protocol. SocketProtocol is an interface which enables sendMessage and receiveMessage (along with a few others).
At this point, the user of the class should just implement SocketProtocol and pass the class (i.e. MySocketProto.class) to the SocketServer instance, which will in turn instance a copy of the protocol for each incoming connection via .newInstance();
Does this make sense? Is there an easier way to establish this type functionality? I don’t like the idea of passing the class type to the server, it just seems odd.
Thanks all,
Chris
I would use the Factory pattern in this situation. The linked Wikipedia example is a bit verbose, but it can be really simple:
Your
SocketServerconstructor would then take an instance of something implementingISocketProtocolFactory, and ask it for newISocketProtocols as it goes.This will give your users a lot more flexibility in constructing the
ISocketProtocolinstances, take care of the ‘nastiness’ of having a class parameter.