首页 > 解决方案 > Ada:如何组织嵌套包

问题描述

假设我们有一辆车,它从 IMU 获取位置。IMU 包由几个私有组件组成,它通过编排来计算车辆在空间中的状态:

with IMU; use IMU;
Package Vehicle is
...
end vehicle; 

Package IMU is

    type Attitude is record
        Lat, Lon: Angle;
        Pitch, Roll, Yaw: Angle;
        GroundSpeed: Speed;
        ...
    end record
    
    function Get_Position return Attitude is ...
    
    Package GPS is
    ...
    end GPS;
    
    Package Accelerometer is
    ...
    end Accelerometer;
    
    Package Gyro is
    ...
    end Gyro;
end IMU;

GPS、加速度计和陀螺仪的内部结构仅在 IMU 的上下文中才有意义;它们必须对车辆完全隐藏。

在单个源文件中声明 IMU 及其所有子组件将难以阅读和维护;我希望每个子组件都在它自己的源文件中。如果我在 IMU 级别将它们全部编码,车辆将能够访问 GPS,这是错误的。

构建嵌套包的最佳实践是什么?

标签: packagestructureada

解决方案


有几种方法可以构建代码,但我不会使用嵌套包,而是为每个“组件”使用一个私有子级。

这样,每个组件都将位于其自己的单元中,并且可以从其父级及其兄弟实现中看到。

您的代码将是

Package IMU is

    type Attitude is record
        Lat, Lon: Angle;
        Pitch, Roll, Yaw: Angle;
        GroundSpeed: Speed;
        ...
    end record
    
    function Get_Position return Attitude is ...
        
end IMU;

private package IMU.GPS is
    ...
end IMU.GPS;

private package IMU.Accelerometer is
    ...
end IMU.Accelerometer;
    
private package IMU.Gyro is
    ...
end IMU.Gyro;

有关其他示例,请参阅wikibook


推荐阅读