1. 概述
在面向对象的程序设计中,类共有六种关系,它们分别是Composition、Aggregation、Association、Dependency、Generalization和Realization。理解类的六大关系对于面向对象的程序设计非常重要,也是理解设计模式的前提。本文给出概念介绍并结合C++代码给出解释,由于作者本身能力有限,难免有不当甚至错误,欢迎指出。文中给出的实例的完整工程详见参考文献1。
2. 组合(Composition)
Composition是一种 "part-of" 的关系,如下图中的孕妇和婴儿。它是一种强所属关系,整体与部分往往具有相同的生命周期,整体的对象是在部分对象创建的同时或创建之后创建,在部分对象销毁的同时或之前销毁。
Composition.jpg
参考代码如下,讲的是游戏中每个生物体(Creature)都有自己的坐标位置,其中坐标位置用Point类表示,明显是一种"part-of"的关系。
#include <string>
struct Point
{
Point() : x(0), y(0) { }
void setPoint(const int x, const int y)
{
this->x = x;
this->y = y;
}
int getPointX() const
{
return this->x;
}
int getPointY() const
{
return this->y;
}
private:
int x;
int y;
};
struct Creature
{
Creature() : name(""), location(location) { }
void setCreature(const std::string& name, const Point& location)
{
this->name = name;
this->location = location;
}
void move(int x, int y)
{
this->location.setPoint(x, y);
}
std::string getName() const
{
return this->name;
}
int getXLocation() const
{
return this->location.getPointX();
}
int getYLocation() const
{
return this->location.getPointY();
}
pr