学习笔记,个人理解。
一、组合
构建一个计算机类,含CPU、硬盘、和内存属性,CPU用自定义类类型表示。
class Cpu
{
public:
Cpu(std::string cpuBrand, std::string cpuDomFre) :_cpuBrand(cpuBrand), _cpuDomFre(cpuDomFre)
{
std::cout << __FUNCTION__ << std::endl;
}
~Cpu()
{
std::cout << __FUNCTION__ << std::endl;
}
private:
std::string _cpuBrand; // 品牌
std::string _cpuDomFre;// 主频
};
class Computer
{
public:
Computer(const std::string cpuBrand, const std::string cpuDomFre,
int hardDisk, int memory):_cpu(cpuBrand, cpuDomFre),_hardDisk(hardDisk),_memory(memory)
{
std::cout << __FUNCTION__ << std::endl;
}
~Computer()
{
std::cout << __FUNCTION__ << std::endl;
}
private:
Cpu _cpu; //computer 和 cpu 之间为组合关系
int _hardDisk; //硬盘
int _memory; //内存
};
int main()
{
Computer computer("酷睿i7", "2.85GHz", 1024, 16);
}
或者Cpu在堆中开辟内存,用指针表示。代码如下:
class Cpu
{
public:
Cpu(std::string cpuBrand, std::string cpuDomFre) :_cpuBrand(cpuBrand), _cpuDomFre(cpuDomFre)
{
std::cout << __FUNCTION__ << std::endl;
}
~Cpu()
{
std::cout << __FUNCTION__ << std::endl;
}
private:
std::string _cpuBrand; // 品牌
std::string _cpuDomFre;// 主频
};
class Computer
{
public:
Computer(const std::string cpuBrand, const std::string cpuDomFre,
int hardDisk, int memory):_cpu(new Cpu(cpuBrand, cpuDomFre)),_hardDisk(hardDisk),_memory(memory)
{
std::cout << __FUNCTION__ << std::endl;
}
~Computer()
{
delete _cpu;
std::cout << __FUNCTION__ << std::endl;
}
private:
Cpu* _cpu; //computer 和 cpu 之间为组合关系
int _hardDisk; //硬盘
int _memory; //内存
};
int main()
{
Computer computer("酷睿i7", "2.85GHz", 1024, 16);
}
运行结果:
具体组合方式:
1、被组合的对象直接使用成员对象;
2、使用类类型指针表示被组合的对象,在构造函数中创建被组合的对象,析构函数中释放被组合的对象。
二、聚合
例子:还是之前的组合例子,继续给计算机接一个音响,音响脱离此计算机还可以为其他计算机使用。计算机坏了(销毁)并不会给音响造成什么影响。
他们只是使用关系,不是组成关系,称为聚合。
class VoiceBox
{
public:
VoiceBox()
{
std::cout << __FUNCTION__ << std::endl;
}
~VoiceBox()
{
std::cout << __FUNCTION__ << std::endl;
}
};
class Cpu
{
public:
Cpu(std::string cpuBrand, std::string cpuDomFre) :_cpuBrand(cpuBrand), _cpuDomFre(cpuDomFre)
{
std::cout << __FUNCTION__ << std::endl;
}
~Cpu()
{
std::cout << __FUNCTION__ << std::endl;
}
private:
std::string _cpuBrand; // 品牌
std::string _cpuDomFre;// 主频
};
class Computer
{
public:
Computer(const std::string cpuBrand, const std::string cpuDomFre,
int hardDisk, int memory):_cpu(cpuBrand, cpuDomFre),_hardDisk(hardDisk),_memory(memory)
{
std::cout << __FUNCTION__ << std::endl;
}
~Computer()
{
std::cout << __FUNCTION__ << std::endl;
}
void addVoiceBox(VoiceBox* box)
{
_box = box;
}
private:
Cpu _cpu; //computer 和 cpu 之间为组合关系
int _hardDisk; //硬盘
int _memory; //内存
VoiceBox* _box;
};
int main()
{
Computer computer("酷睿i7", "2.85GHz", 1024, 16);
VoiceBox box;
computer.addVoiceBox(&box); // 增加音响
}
运行结果:
计算机销毁后,音响并没有销毁。
具体组合方式:
被聚合的对象使用成员对象指针。
总结:
组合关系:
CPU的生命周期和computer生命周期一致,
computer创建时,cpu也创建,
computer销毁时,cpu也销毁。
拥有者需要对被拥有者负责,是一种比较强的关系,是整体与部分的关系。
聚合关系:
聚合不是组成关系,被包含的对象,也可能被其他对象包含。
拥有者,不需要对被拥有的对象的生命周期负责。