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.
enter image description here enter image description here
(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?
1 Answer 1
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
and SuperType
. Option 2 would mean SomeClass
has 3 attributes one for each of Class1
, Class2
and Class3
, which is not what you want.
-
Good answer. I would also add that "SomeClass" should only know that it is talking to a "SuperType" class and not know that it is really talking to a Class1, Class2 or Class3 class. Option 1 conveys this but option 2 says exactly opposite.Dunk– Dunk2014年04月08日 14:18:24 +00:00Commented Apr 8, 2014 at 14:18