(软件设计) has-a 的三种形式(组合、聚合、关联)

👣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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天赐细莲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值