Programming Tips: Know your UML Class Diagram Relationships
The various types of relationships used between classes in UML class diagrams represent many of the ways classes and other objects can interact in actual code. As such, having a working knowledge of these relationships and the kind of source code they can represent can be extremely useful. When you figure out what sort of UML relationship best represents the way two classes interact, you answer several crucial questions (Is class A a base class for class B or should class A hold an instance of class B? What is the lifetime of the classes involved? Are these classes shared? ) that can dictate just what sort of code you should be writing.
Here is a quick cheat sheet of the relationships I use most often and the sort of code I end up deriving from them:
GENERALIZATION
The classic “is-a” relationship of class inheritance.
![]()
class A : public class B
{
};
COMPOSITION
The most common form of “has-a” class relationships. The important point here being that the lifetime of the owned class is tied to its parent.
![]()
class C
{
D m_ChildClass;
};
Or, for the pointer-lovers out there:
class C
{
D* m_pChildClass;
};
C::C()
{
m_pChildClass = new D;
}
C::~C()
{
delete m_pChildClass;
}
AGGREGATION
The other white meat of “has-a” relationships. I generally use this notation to distinguish objects to which I potentially share references from those whose lifetime I directly control.
![]()
class E
{
F* m_pChildClass;
};
void E::SetInstanceOfF( F* pChildClass )
{
m_pChildClass = pChildClass;
if( m_pChildClass )
{
m_pChildClass->AddReference();
}
}
void E::RemoveReferenceToF()
{
if( m_pChildClass )
{
m_pChildClass->RemoveReference();
m_pChildClass = NULL;
}
}
ASSOCIATION
The association notation is a bit more general purpose and vague than the relationships above and generally has extra text describing the specifics of what it represents in a given diagram. I often use it to highlight relationships in which classes don’t take any particular responsibility each others’ lifetimes. For example, a class that regularly accesses a global singleton, assuming that it is always around and never needs any special reference handling.
![]()
class G : public class Singleton<G>
{
};
class H
{
};
void H::H()
{
m_Id = G::GetSingletonInstance().GetUniqueId();
}
DEPENDENCY
The weakest of UML class relationships, dependency indicates that one class merely makes use of another class and probably doesn’t keep it around persistent in memory for any significant amount of time.
![]()
class I
{
};
void I::DoSomething()
{
J temporaryJ;
m_Something = temporaryJ.DoSomethingWithJ();
}
English
日本語
Russian Blue