UML Design class diagram: Class with another class

2019-07-03 14:32发布

问题:

I'm having a pretty hard time trying to figure out how to model a certain scenario as a UML design class diagram.

Suppose I have the following situation:

I have a class named CPoint that has two attributes: x and y (coordinates in a R2 plane). In the other hand, I have a class named CLine that should have two CPoint as attributes.

This is pretty straight forward to code (I'll use C++ in my example):

class CPoint{
    float x;
    float y;
    //Constructor, gets and sets here
}

And for CLine:

class CLine{
    CPoint p1;
    CPoint p2;
    //Constructor, gets and sets here
}

Now my question is: How do I model such a thing in UML?

I thought of something similar to this:

But then I was told that this is violating the principles of object oriented modeling, so then I did this:

But It does not convince me at all. Additionally, I was reading about design patterns and came to this UML design while reading about singletons:

Which makes me think my initial approach was just right. Additionally, I'm able to see that my first approach is just alright if I thing about it as a C++ program. In java however, I'd still have to create the object by doing new CPoint(0, 0) in the CLine's constructor. I'm really confused about this.

So, how do I model this situation? Am I perhaps being too concrete when I attempt to model the situation?

Thanks in advance! This isn't letting me sleep at night

回答1:

In UML an association or an attribute (property) are more or less the same thing, so they are both correct.

In most UML tools however they are different things.

There is not really a rule here, but there are best practices. My UML Best Practice: Attribute or Association says:

Use Associations for Classes and Attributes for DataTypes



回答2:

If your CLine has exactly two ends represented by point, than you can define it in UML as class CLine with attributes (just like your CLine on the first example is OK but without association "has") or you can design it as CLine class with two association to CPoint. Multiplicity at CPoint will be 1 with role p1 for the first one and p2 for the second one at the CPoint side.



回答3:

There is not one best solution. It depends on the context and what you want to model. I agree with Vladimir that you would have two relations with roles p1 and p2. The members x and y should be private I guess (-x, -y) and not public (+x, +y). Furthermore you could model the relation as aggregate or composite (open or closed diamond symbol) but if a single point can be the endpoint of two lines then that is not appropriate. Again, this depends on what you want to model. If construct a new point in the line constructor as stated in the question, then you probably want to use a composition relation as these points do not exist without the line.

(Btw, in the code the coordinates are float and in the diagram ints).