👣has-a
在软件设计中有一句设计原则“组合优于继承”。继承通常用is a表示,组合通常用has a表示。
但要更进一步了解has a 的话,可以再继续细分为三种类型:
- 组合(Composition)
- 聚合(Aggregation)
- 关联(Association)
👣组合、聚合、关联
我们直接来看一个例子,用一个汽车类来进行表述。
#include <iostream>
#include <string>
// 引擎
struct Engine {
void start() {
std::cout << "Engine started" << std::endl;
}
};
// 轮子
struct Wheel {
void rotate() {
std::cout << "Wheel rotating" << std::endl;
}
};
// 驾驶员
struct Driver {
std::string name;
Driver(const std::string& name) : name(name) {
}
};
// 车
class Car {
private:
Engine engine; // Car has an Engine (Composition relationship)
Wheel* wheel = nullptr; // Car has a Wheel (Aggregation relationship)
Driver* driver = nullptr; // Car is associated with a Driver (Association relationship)
public:
Car(Wheel* wheel) : wheel(wheel) {
}
void sitDown(Driver* driver) {
this->driver = driver;
}
public:
void start() {
if (driver

&spm=1001.2101.3001.5002&articleId=145599850&d=1&t=3&u=383fb04a94a042a08a63fb72f597362d)
270

被折叠的 条评论
为什么被折叠?



