views:

28

answers:

2

Hi Everyone,

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

+1  A: 

I would use the Factory pattern in this situation. The linked Wikipedia example is a bit verbose, but it can be really simple:

public interface ISocketProtocolFactory {
    ISocketProtocol buildProtocol();
}

Your SocketServer constructor would then take an instance of something implementing ISocketProtocolFactory, and ask it for new ISocketProtocols as it goes.

This will give your users a lot more flexibility in constructing the ISocketProtocol instances, take care of the 'nastiness' of having a class parameter.

Shtééf
I like this idea.. and it does take care of the class parameter. So, let me get this straight, would ISocketProtocolFactory implementations instance the user implementation of ISocketProtocol and then return the instantiated object?
Chris Kannon
That's right. You could even add parameters to `buildProtocol`, and the user may return different implementations of `ISocketProtocol` in certain scenarios. But in most cases it's just `return new MySocketProtocol()`.
Shtééf
Sweet. Thanks. Sounds like the factory design pattern fits the requirements. I'm familiar with it, but didn't think to use it for this situation!
Chris Kannon
A: 

I would assume that each port would have it's own protocol. With that in mind you would specify it for the port.

The way I had done it in the past is to have the implementors pass in a class that inherits from:

public Interface ProtocolInterface
{
   public void serve(InputStream in, OutputStream out) throws IOException
...

where the InputStream and OutputStream are the input and outputs to the Socket

Romain Hippeau