工厂设计模式 - 不使用静态方法,因为单元测试是一个问题

Pra*_*nna 15 java junit design-patterns factory-pattern

我知道这个问题已在stackoverflow中被多次询问,但不知何故仍然在找出解决方案时遇到一些麻烦.我认为以下示例是一个使用静态方法的好例子

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;
    }

    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

假设我有如下的CommunicationService

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
}
Run Code Online (Sandbox Code Playgroud)

像这样,不同的通信服务可以创建和维护多种类型的连接.

我想测试initConnectionPool方法,在单元测试环境中,套接字创建肯定会失败.

我可以将ConnectionFactory更改为具体类并将其模拟出来.但是这种情况不是用静态方法创建类的好情况吗?我不是要在ConnectionFactory中维护任何状态.那么,如果我们使用静态方法时使用静态方法可能会导致测试问题?或者在这里使用静态方法是不合适的?

编辑:解决方案我去了

public class CommunicationService
{
    public void initConnectionPool(ConnectionType connectionType)
    {
        for(int i = 0; i < MAX_CONNECTIONS; i++)
             connectionList.add(connectToHost(connectionType));

        //Some more code here to do further processing
          ......
          ......
    }    

    public Connection connectToHost(ConnectionType connectionType)
    {
        ConnectionFactory.createConnection(connectionType, "domain.com", 40203)
    }
    //Some more methods
}
Run Code Online (Sandbox Code Playgroud)

在测试中覆盖了connectToHost并返回了一个模拟.

Nrj*_*Nrj 1

我认为在这里使用静态方法更好。

在测试环境或任何其他环境中 - ConnectionFactory 应使用不同的属性集进行初始化。

因此,实际上,您应该针对不同的环境拥有不同的属性集(包含连接类型、端口等),并且您可以使用适当的属性进行初始化。