Enforce single-entry collections in single-entry instance of composed object
<p>I have an abstract class that implements an interface.  I then have several classes that extends that abstract class that are in turn composed of a hierarchy of some objects plus one or more Lists of objects extending the same abstract class, repeated for some levels.  In essence,</p>

<pre><code>public interface Bar

public abstract class BarImpl implements Bar

public class Foo extends BarImpl {

  private String value1;
  private String value2;
  private List&lt;Foo2&gt; fooSubs;

  public List&lt;Foo2&gt; getFooSubs() {
    return fooSubs;
  }
}

public class Foo2 extends BarImpl {
  private String value3;
  private String value4;
  private List&lt;Foo3&gt; fooSubs;

  public List&lt;Foo3&gt; getFooSubs() {
    return fooSubs;
  }
}

...etc...
</code></pre>

<p>The data in question is actually X12 healthcare claim data for those who are familiar.  I've defined a Loop interface to correspond to the various loops that compose the X12 file.</p>

<p>My issues is this - I need to also be able to describe a single transaction, in theory using the same object or some wrapper on that object, where for some specified depth the size of each list of objects is 1.</p>

<p>My first though is/was to add a boolean singleTransaction to the BarImpl abstract class.  Each class extending that would then have a check on the addFoo methods to make sure that the object did not grow beyond the single entry.  Before converting to FooSingle I would check as well.</p>

<pre><code>public void addFoo(Foo foo) throws FooException {
    if (singleTransaction &amp;&amp; fooSubs.size() &gt;= 1)
        throw new FooException();
    else
        fooSubs.add(foo);
}
</code></pre>

<p>I would also have to remove the setFoo method, so as to prevent an already-populated List from being assigned.  Perhaps just make it final...</p>

<p>Does this seem like a reasonable way to go about this?  I could then have a SingleBarImpl class that would verify it had a single path down the hierarchy, filter the boolean down, and could then safely assume that there was only one object-per-list for the specified classes.  This could then simplify the access to the hierarchy since I no longer needed to worry about multiple list entires.</p>

<p>This feels very ugly is why I raise the question, and I wasn't quite sure what I should search on for an alternative.  So I decided to stop lurking, create an account, and throw this out there.  So...any ideas?  Am I missing some design pattern that makes this much more elegant?</p>
