开发者

Enforce single-entry collections in single-entry instance of composed object

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,

public interface Bar

public abstract class BarImpl implements Bar

public class Foo extends BarImpl {

  private String value1;
  private String value2;
  private List<Foo2> fooSubs;

  public List<Foo2> getFooSubs() {
    return fooSubs;
  }
}

public class Foo2 extends BarImpl {
  private String value3;
  private String value4;
  private List<Foo3> fooSubs;

  public List<Foo3> getFooSubs() {
    return fooSubs;
  }
}

.开发者_StackOverflow..etc...

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.

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.

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.

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

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...

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.

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?


I am not familiar with X12 healthcare claim data and hence can't properly model the domain, but it sounds like you want to use the GOF composite pattern . A "Leaf" implementation class could easily replace your "singleTransaction" flag

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜