2012-02-15 67 views
1

如果我有一个客户端定义如下: -吉斯模块配置的具体类

public interface Client { 
    void send(String message); 
} 

和实施如下: -

final class SocketClient { 

    private Integer port; 

    @Inject 
    SocketClient(Integer port) { 
     this.port = port; 
    } 

    @Override 
    public void send(String message) { 
     System.out.println("Sending message:- "+message+" to port "+port); 
    } 
} 

我将如何使用吉斯实例的多个实例SocketClient,每个连接到不同的端口?

回答

2

,想到的第一个解决方案是创建一个SocketClientFactory界面,看起来像

interface SocketClientFactory { 
    SocketClient createForPort(int port); 
} 

,然后开始使用assisted injection extension工厂实例。

+0

辅助注射看起来像我之后。 – Martin 2012-02-15 21:58:47

1

你将不得不实现类似于一个单独的PortAllocator,它跟踪它已经分配的端口。然后,您可以注入到这一点你的客户:使用一个接口,如果你喜欢

@Singleton 
class PortAllocator { 
    private int nextPort = 1234; 

    int allocatorPort() { 
    return nextPort++; 
    } 
} 

你可以取消夫妇:

@Inject 
SocketClient(PortAllocator portAllocator) { 
    this.port = portAllocator.allocatePort(); 
} 

PortAllocator可能看起来像。您可能也想考虑线程安全性。

你可能会争辩说,你在这里并没有从Guice那里得到太多的东西,但是你得到了内建的单身状态管理和缺乏静态信息使测试变得简单。

+0

很好的答案,但我知道我想连接的端口。 – Martin 2012-02-15 21:59:43

+0

是的,我的解释稍有不同。 AssistedInject或工厂模式确实看起来是正确的方法。 – 2012-02-16 17:55:39