一般我们可以把类之间的关系分为两种:纵向关系和横向关系。纵向关系就是继承,横向关系又可以分为四种:组合、关联、依赖和聚合。组合>关联>依赖。
1.组合
组合也是类之间关系的一种特例,它体现的是一种关系,这种关系比任何关系都更强,它体现整体与部分之间的关系,但此时整体与部分是不可分的,整体的生命周期结束也就意味着部分生命周期的结束,比如人和人的大脑。表现在代码层次。和关联关系的一致,只能从语义级别来区分,在UML类图设计中组合关系实形菱形加箭头表示。
#include<iostream>
using namespace std;
class Head
{
public:
void Say()
{
}
};
class Hand
{
public:
void Move()
{
}
};
class Person
{
public:
Hand hand;
Head head;
public:
void Meeting()
{
head.Say();
hand.Move();
}
};
int main()
{
return 0;
}
2.关联
关联是两个之间语义级别的一种关系,不存在关系的偶然性,关系也不是临时性的,一般是长期性的,而且双方的关系一般。出现在关联类中,也可能是关联类中引用的一个类行为被关联类的全局变量。在UML类图设计中,关联关系由带箭头实型线表示。
#include<iostream>
using namespace std;
class Friend
{
public:
int Rp;
public:
Friend(int n)
{
this->Rp = n;
}
void Say()
{
cout << "你好" << endl;
}
};
class Person
{
public:
Friend* pfriend;
public:
void SetFriend(Friend* pFriend)
{
if (pFriend->Rp>60)
{
this->pfriend = pFriend;
}
else
{
cout << "人品不好" << endl;
}
}
void Say()
{
if (this->pfriend!= NULL)
{
pfriend->Say();
cout << "您好" << endl;
}
else
{
cout << "没交上" << endl;
}
}
};
int main()
{
Friend f(80);
Person ps;
ps.Say();
return 0;
}
3.依赖
依赖就是一个类A使用到了一个类B,而这种使用关系是具有偶然性的、临时性的,非常弱的。但是类B的变化会影响到类A,比如某人要打代码。需要用一台电脑,此时人与电脑之间的关系就是依赖表现在代码层面,位类A的某个变量作为参数,被类B在某个方法中使用。在UML类图设计中,依赖关系用由类指向类,另一个类的带箭头虚线表示。
#include<iostream>
using namespace std;
class Computer
{
public:
void Debug()
{
cout << "#include……" << endl;
}
};
class Person
{
public:
void Code(Computer* pComputer)
{
pComputer->Debug();
}
};
int main()
{
Computer Com;
Person ps;
ps.Code(&Com);
return 0;
}
4.聚合
聚合是关联关系的一种特例,它体现的是整体与部分的关系啊。此时,整体与部分之间是可分离的,它们可以具有各自的生命周期,部分可以属于多个整体对象。也可以有多个整体对象共享,比如计算机与CPU,公司与员工的关系等,比如一个航空编队,包括航空母舰、驱护舰艇、舰载飞机及核动力攻击潜艇等。表现在代码层面和关联关系是一致的,只能从语义级别来去区分。在UML类图设计中,聚合关系空心菱形加实线箭头表示。
#include<iostream>
using namespace std;
class Person
{
public:
void Play()
{
cout << "幸福" << endl;
}
};
class Family
{
public:
Person* arr[10];
public:
Family()
{
for (int i = 0; i < 10; i++)
{
arr[i] = NULL;
}
}
public:
void PushPerson(Person* pPs)
{
for (int i = 0; i < 10; i++)
{
if (arr[i] == NULL)
{
arr[i] = pPs;
return;
}
}
cout << "没位置了" << endl;
}
public:
void Print()
{
for (int i = 0; i < 10; i++)
{
if (arr[i] != NULL)
{
arr[i]->Play();
}
else
{
cout << "——NULL———" << endl;
}
}
}
};
int main()
{
Family fa;
Person ps1, ps2, ps3;
fa.PushPerson(&ps1);
fa.PushPerson(&ps2);
fa.PushPerson(&ps3);
fa.Print();
return 0;
}