Java Reference
In-Depth Information
factory object supplies instances of a particular class, hiding the details of how the instance
is created, such as what constructor is used.
For our protocol factory, we define the ProtocolFactory interface to have a single method,
createProtocol() , which takes Socket and Logger instances as arguments and returns an
instance implementing the desired protocol. Our protocols will all implement the Runnable
interface, so that once we have an instance we can simply call run() (or start() on a Thread
constructed from the protocol instance) to execute the protocol for that connection. Thus, our
protocol factory returns instances that implement the Runnable interface:
ProtocolFactory.java
0 import java.net.*; // for Socket
1
2 public interface ProtocolFactory {
3
public Runnable createProtocol(Socket clntSock, Logger logger);
4 }
ProtocolFactory.java
We now need to implement a protocol factory for the echo protocol. The factory class is
simple. All it does is return a new instance of EchoProtocol whenever createProtocol() is called.
EchoProtocolFactory.java
0 import java.net.*; // for Socket
1
2 public class EchoProtocolFactory implements ProtocolFactory {
3
public Runnable createProtocol(Socket clntSock, Logger logger) {
4
return new EchoProtocol(clntSock, logger);
5
}
6 }
EchoProtocolFactory.java
We have factored out some of the details of protocol instance creation from our server,
so that the various iterative and concurrent servers can reuse the protocol code. However,
the server approach (iterative, thread-per-client, etc.) is still hard-coded in the main() . These
server approaches deal with how to dispatch each connection to the appropriate handling
mechanism. To provide greater extensibility, we want to factor out the dispatching model from
the main() of TCPEchoServerThread.java so that we can use any dispatching model with any
protocol. Since we have many potential dispatching models, we define the Dispatcher interface
to hide the particulars of the threading strategy from the rest of the server code. It contains a
 
Search WWH ::




Custom Search