HighlightableStructure

HighlightableStructure

本文介绍了有什么好方法可以使不可变对象链环回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是 this的扩展问题.

我有一个与以下相似的课程.

I have a class similar to the following.

 class HighlightableStructure {
      private final HighlightableStructure NEXT;

      HighlightableStructure(HighlightableStructure next) {
           NEXT = next;
      }
 }

,其中HighlightableStructure指向要突出显示的下一个结构.

where a HighlightableStructure points to the next structure to highlight.

有时,这些HighlightableStructure循环并引用先前的HighlightableStructure,但不是链中的第一个.类似于h_1-> h_2-> h_3-> ...-> h_n-> h_2,其中h_i是HighlightableStructure的实例.

Sometimes, these HighlightableStructures loop around and refer to a previous HighlightableStructure, but not the first in the chain. Something like h_1 -> h_2 ->h_3 -> ... -> h_n -> h_2, where h_i is an instance of HighlightableStructure.

无论如何,我是否可以构造这样的东西而不会产生反射或失去不变性?

Is there anyway I could construct something like this without reflection or losing immutability?

推荐答案

一种可能的解决方案:

class HSequenceBuilder {
    private long id = 0;
    private final Map<Integer, H> map = new HashMap<Integer, H>();

    static H create(int next) {
        H h = new H(id, next, Collections.unmodifiableMap(map));
        map.put(id, h);
        id++;
        return h;
    }

    static H create() {
        create(id + 1);
    }

}

class H {
    private final id;
    private final Map<Integer, H> map;
    private final int next;

    H(int id, int next, Map<Integer, H> map) {
        this.id = id;
        this.next = next;
        this.map = map;
    }

    int getId() { return id; }
}
HSequenceBuilder builer = new HSequenceBuilder();
H h1 = builder.create(); // 1.
H h2 = builder.create(); // 2.
H h3 = builder.create(h2.getId()); // 3.

这篇关于有什么好方法可以使不可变对象链环回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 08:34