类图是代码结构的主要建模形式,为了让读者看的更形象,采用图例的方式介绍类图和代码的映射关系。
如下是一个设计类图的图例:

下面对类之间的关系分别进行类图和代码示例说明( C++ 代码):
1) Association
2) Aggregation
3) Composition
4) Generalization
5) Realization
6) Dependency
类的关系:
Association
Driver 可以驾驶 Car ,二者的关系长期存在。
 |
#include "Car.h"
class Driver
{
public:
Driver();
virtual ~Driver();
Car *m_Car; //assocation关系
void Drive();
private:
int name;
int age;
}; |
Aggregation
Car 聚合了 Wheel , Wheel 可以脱离 Car 而独立存在。
 |
class Car : public Device
{
public :
Car ();
virtual ~ Car ();
Wheel * m_Wheel ; //aggregation 关系
Motor m_Motor ;
void Move ();
private :
int mass ;
int rate ;
};
|
Composition
Car 包含 Motor , Motor 是 Car 不可分的一部分。
 |
#include "Wheel.h"
class Car : public Device
{
public :
Car ();
virtual ~ Car ();
Wheel * m_Wheel ;
Motor m_Motor ; //composition 关系
void Move ();
private :
int mass ;
int rate ;
}; |
Generalization
Motor 和 Wheel 是 Device 的子类,继承了 Device 的属性: id 和 state ,方法: Start ()和 Stop()
 |
#include "Device.h"
class Wheel : public Device
{
public :
Wheel ();
virtual ~ Wheel ();
void Rotate ();
private :
int radius ;
int width ;
}; |
Realization
Device 实现 接口 Runnable 的 Start ()和 Stop ()方法。
|
#include "Runnable.h"
class Device : public Runnable //Realization 关系
{
public :
Device ();
virtual ~ Device ();
int id ;
int state ;
void Start ();
void Stop ();
}; |
Dependency
Car 的 move 操作依赖于 enviroment
 |
#include "Wheel.h"
#include "environment.h"
class Car
{
public :
Car ();
virtual ~ Car ();
Wheel * m_Wheel ;
Motor * m_Motor ;
void Move ( enviroment e ); //dependency 关系
private :
int mass ;
int rate ;
}; |
|