Please consider a program with four classes: Class A, B, C and D.
Classes A and B are subclasses of abstract super-class C.
Class D is dependent on C. Meaning: It holds a C objectOfTypeC
field.
As we know, polymorphically the objectOfTypeC
reference may hold objects of classד A and B. The value of this reference may change dynamically during runtime.
This kind of situtation is very common in OOP.
A common example is the Strategy pattern, where several classes all inherit or implement the abstract-class or interface SuperType
. Another class SomeClass
holds a reference of type SuperType
, and is able to dynamically hold different instances of SuperType
subclasses in that reference.
My question is this: I have two ideas how this can be shown in a UML class diagram, but I'm not sure which one is correct.
(Please note: in these examples, the super type is an interface, but it could also be an abstract class, or even a regular super class).
Which option is more correct?
Best Answer
If you look at UML of strategy pattern you mentioned, you will notice Option 1 is correct. To explain it properly. In UML, the association relation (eg. the arrow) usually means the entity has attribute that is of type the arrow is pointing at. Which is exactly your case of association between
SomeClass
andSuperType
. Option 2 would meanSomeClass
has 3 attributes one for each ofClass1
,Class2
andClass3
, which is not what you want.