简体   繁体   中英

How should I model associations between classes

I am modelling the domain model in my application. Obviously, some of the object relationships are assocations, but those associations also have attributes. For example:

Foo can have one-to-many Bars. However, the association has attributes, such as a date range for how long that association is valid. So, the way I have done this is as follows:

public interface Association<S, T> {
     public S getSource();

     public T getTarget();
}

Then for something like the above:

public class FooToBarAssociation implements Association<Foo, Bar> {
    public Foo getSource();
    public Bar getTarget();
    public Date getFromDate();
    public Date getToDate();
}

Then the Foo class has:

private List<FooToBarAssociation> associations;

My questions are:

  1. Is this an appropriate way to model the association with attributes?

  2. Where should the business logic be for adding/removing the associations to Foo? Creating a FooToBarAssociation will sometimes require a bit of business logic and I'm wondering if that should be handled in a FooService, which then calls setAssociations rather than being in the model object. I've always heard to keep biz logic out of the model objects as much as possible.

Answers to your questions:

  1. I think your model is appropriate.
  2. In a domain oriented model, I would add the association logic to Foo.

I have another suggestion, but it applies to a specific situation. If you need the model to work with only one association at a time the following simplified model would work.

public class Foo {

    private Date startDate;
    private Date endDate;
    private Bar bar;

    public Date getStartDate() {
        return startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public Bar getBar() {
        return bar;
    }


}

where the start and end dates correspond to the period for which bar is associated with Foo. This way, even though Foo to Bar is one to many, you would only work on one Bar at a time. The Foo Bar association would be fetched from the database, based on an effective date, which would lie between start and end dates.

IMHO same rules apply as when you implement association classes in UML. What you created is one way, other might be nesting - Foo contains Assoc which in turn contains Bar. You can create it also the other way around Bar containing Assoc and Assoc containing Foo. Foo can contain Assoc and Bar can contain Assoc. There are many possibilities, it depends only on you requirements. In your example your solution looks good. What you heard seems good, but sometimes it might be complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM