美文网首页
【随笔·技术】Creating circular generic

【随笔·技术】Creating circular generic

作者: 子寤 | 来源:发表于2017-08-11 23:10 被阅读13次

    文章取自stackeoverflow上的一个问题的回答,链接在这里


    Circular generic references are indeed possible. Java Generics and Collections includes several examples. For your case, such a specimen would look like this:

    public interface P2PNetwork<N extends P2PNetwork<N, C>,
                                C extends P2PClient<N, C>> {
      void addClient(C client);
    }
    
    public interface P2PClient<N extends P2PNetwork<N, C>,
                                C extends P2PClient<N, C>> {
      void setNetwork(N network);
    }
    
    class TorrentNetwork implements P2PNetwork<TorrentNetwork, TorrentClient> {
      @Override
      public void addClient(TorrentClient client) {
        ...
      }
    }
    
    class TorrentClient implements P2PClient<TorrentNetwork, TorrentClient> {
      @Override
      public void setNetwork(TorrentNetwork network) {
        ...
      }
    }
    
    ...
    
    TorrentNetwork network = new TorrentNetwork();
    TorrentClient client = new TorrentClient();
    
    network.addClient(client);
    

    相关文章

      网友评论

          本文标题:【随笔·技术】Creating circular generic

          本文链接:https://www.haomeiwen.com/subject/qafdrxtx.html