lundi 4 janvier 2016

Extensible interface for different models

I'm designing an API which defines a common interface between two different models. The common interface is a Peer which represents an external system to communicate with. A Client is a Peer which attempts to establish a connection to a specific address. And a Server is a Peer which accepts connections in from a subnet of addresses.

public interface Peer {
    void send(Message m);
}

public interface Client extends Peer {
    InetAddress getAddress();
}

public interface Server extends Peer {
    String getSubnet();
}

Applications that use this API will work with Peer objects. Because of this, their logic will constantly require type checking to pull information unique to the Peer to perform their work. Furthermore, if there ever became another type of Peer applications may break.

Peer p = incomingMessage.getPeer();

if (p instanceof ClientPeer) {
    //do client peer stuff
} else if (p instanceof ServerPeer) {
    //do server peer stuff
} else {
    //uh oh...
}

Is there a cleaner way to design this? One that does not require constant type checking, and isn't flawed from expanding itself further with new types of Peer?

Aucun commentaire:

Enregistrer un commentaire