I know this question has been asked several times in stackoverflow but somehow still had some trouble figuring out a solution. The following example I think is a good case to have static methods
public class ConnectionFactory
{
public static Connection createConnection(ConnectionType connectionType, String ipAddr, Integer port)
{
//Some error checking
switch(connectionType)
{
case TCP:
return createTcpConnection(ipAddr, port);
case UDP:
return createUdpConnection(ipAddr, port);
case RTP:
return createRtpConnection(ipAddr, port);
case SCTP:
return createRtpConnection(ipAddr, port);
default:
break;
}
}
// TcpConnection, RtpConnection, SctpConnection and UdpConnection implement interface Connection
public Connection createTcpConnection()
{
Connection connection = new TcpConnection();
.....
.....
return connection;
}
public Connection createUdpConnection()
{
Connection connection = new UdpConnection();
.....
.....
return connection;
}
....
....
}
And suppose if I have a CommunicationService like the following
public class CommunicationService
{
public void initConnectionPool(ConnectionType connectionType)
{
for(int i = 0; i < MAX_CONNECTIONS; i++)
connectionList.add(ConnectionFactory.createConnection(connectionType, "domain.com", 40203));
//Some more code here to do further processing
......
......
}
//Some more methods
}
Like this, different communication services can create and maintain multiple type of connections.
I want to test initConnectionPool method and in a unit test environment, socket creation will