1.4.2 涉及其他ADT的ADT
前面的两个示例都需要表示日期,预约簿示例还要求表示时间。可以使用C++的ctime中的日期-时间对象表示日期和时间。也可以用面向对象的方式设计ADT表示这些项。设计使用其他ADT的ADT并不少见。实际上,可以使用一个ADT实现其他ADT。
注释:可以使用某个ADT实现其他ADT
最后一个示例描述一个ADT,该ADT的实现需要其他ADT。假定想要设计一个配方数据库。可以将这个数据库当作一个ADT。配方是数据项,某些针对配方的典型操作如下所示:
- // Inserts a recipe into the database.
- +insertRecipe(aRecipe: Recipe): boolean
- // Deletes a recipe from the database.
- +deleteRecipe(aRecipe: Recipe): boolean
- // Gets the named recipe from the database.
- +getRecipe(name: string): Recipe
这种层次的设计不会指明细节,例如insertRecipe将在数据库的什么位置放置某个配方。
现在假定想要设计操作,该操作按比例确定从数据库获取的配方大小:如果配方本来用于n个人,现在想要修改这个配方使其用于m个人。假定配方包含了度量单位,例如21/2杯、1汤匙和1/4茶匙。也就是说,份量使用混合数字(整数和分数)以杯、汤匙、茶匙为单位给定。
这个问题涉及另一个ADT(测量),该ADT具有的操作如下:
- // Returns this measure.
- +getMeasure(): Measurement
- // Sets this measure to another one.
- +setMeasure(m: Measurement)
- // Returns this measure multiplied by a fractional scale factor, which has no units.
- +scaleMeasure(scaleFactor: float): Measurement
- // Returns this measure converted from its old units to new units.
- +convertMeasure(oldUnits: MeasureUnit,
- newUnits: MeasureUnit): Measurement
假定想让ADT测量执行准确的分数运算。由于我们计划使用的语言C++没有分数数据类型,而浮点数并不精确,因此就需要一个分数ADT。其操作可能包含分数的加、减、乘、除。例如,可以将加法指定为:
- // Returns the sum, reduced to lowest terms, of this fraction and the given fraction.
- +add(other: Fraction): Fraction
此外,当方便的时候,可以包含将混合数字转换为分数的操作以及反向操作。当最终实现了ADT测量时,可以使用ADT分数。也就是说,可以使用一个ADT实现另一个ADT。