1 组合
1.1 组合的基本概念
当两个对象之间是整体与部分的关系时,它们之间就是组合的关系。
对于如下问题:
构建一个计算机类,一台计算机,由CPU芯片,硬盘,内存等组成。CPU芯片也使用类来表示。
计算机类和CPU类就是组合关系,组合关系具有如下特点:
- 被拥有的对象(芯片)的生命周期与其拥有者(计算机)的生命周期是一致的。
- 计算机被创建时,芯片也随之创建。
- 计算机被销毁时,芯片也随之销毁。
- 拥有者需要对被拥有者负责,是一种比较强的关系,是整体与部分的关系。
1.2 组合的具体方式
具体组合方式:
1)被组合的对象直接使用成员对象。(常用)
2)使用指针表示被组合的对象,在构造函数中,创建被组合的对象;在析构函数中,释放被组合的对象。
UML中的组合表示:
注意包含者使用实心菱形(UML画图工具:starUML)。
1.3 组合的具体实例
构建一个计算机类,一台计算机,由CPU芯片,硬盘,内存等组成。CPU芯片也使用类来表示。
CPU类:
#pragma once
#include <string>
class CPU
{
public:
CPU(const char *brand = "intel", const char *version="i5");
~CPU();
private:
std::string brand; //品牌
std::string version; //型号
};
#include "CPU.h"
#include <iostream>
CPU::CPU(const char *brand, const char *version)
{
this->brand = brand;
this->version = version;
std::cout << __FUNCTION__ << std::endl;
}
CPU::~CPU()
{
std::cout << __FUNCTION__ << std::endl;
}
Computer类:
#pragma once
#include "CPU.h"
class Computer
{
public:
Computer(const char *cpuBrand, const char *cpuVersion,
int hardDisk, int memory);
~Computer();
private:
CPU cpu; // Computer和CPU是“组合”关系
int hardDisk; //硬盘, 单位:G
int memory; //内存, 单位:G
};
#include "Computer.h"
#include <iostream>
Computer::Computer(const char *cpuBrand, const char *cpuVersion,
int hardDisk, int memory):cpu(cpuBrand, cpuVersion)
{
this->hardDisk = hardDisk;
this->memory = memory;
std::cout << __FUNCTION__ << std::endl;
}
Computer::~Computer()
{
std::cout << __FUNCTION__ << std::endl;
}
main.cpp:
#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
#include "Computer.h"
using namespace std;
void test() {
Computer a("intel", "i9", 1000, 8);
}
int main(void) {
test();
system("pause");
return 0;
}
构造与析构的顺序如下:
Cpu::Cpu
Computer::Computer
Computer::~Computer
Cpu::~Cpu
2 聚合
2.1 聚合的基本概念
聚合不是组成关系,被包含的对象,也可能被其他对象包含。
拥有者,不需要对被拥有的对象的生命周期负责。
UML中的组合表示:
2.2 聚合的具体实例
需求:给计算机配一台音响。
Computer类:
#pragma once
#include "CPU.h"
class VoiceBox;
class Computer
{
public:
Computer(const char *cpuBrand, const char *cpuVersion,
int hardDisk, int memory);
~Computer();
void addVoiceBox(VoiceBox *box);
private:
CPU cpu; // Computer和CPU是“组合”关系
int hardDisk; //硬盘, 单位:G
int memory; //内存, 单位:G
VoiceBox *box; //音箱
};
#include "Computer.h"
#include <iostream>
#include "VoiceBox.h"
Computer::Computer(const char *cpuBrand, const char *cpuVersion,
int hardDisk, int memory):cpu(cpuBrand, cpuVersion)
{
this->hardDisk = hardDisk;
this->memory = memory;
std::cout << __FUNCTION__ << std::endl;
}
void Computer::addVoiceBox(VoiceBox *box) {
this->box = box;
}
Computer::~Computer()
{
std::cout << __FUNCTION__ << std::endl;
}
main.cpp:
#include <iostream>
#include <Windows.h>
#include <string>
#include <string.h>
#include "Computer.h"
#include "VoiceBox.h"
using namespace std;
void test(VoiceBox *box) {
Computer a("intel", "i9", 1000, 8);
a.addVoiceBox(box);
}
int main(void) {
VoiceBox box;
test(&box);
system("pause");
return 0;
}
参考资料: