从面向对象的范式思考,人们如何倾向于为标记记录实现私有属性?
从我可以看到的那一刻起,唯一的方法是拥有一个私有类型的属性.
例如
type car is tagged record
i_am_a_public_attribute : Integer;
i_am_another_public_attribute : Integer;
my_private_attributes : t_private_attributes;
end record;
Run Code Online (Sandbox Code Playgroud)
其中t_private_attributes在包的私有部分中声明.
我想到的第二种方法是使用继承,例如
type car_public is tagged record
i_am_a_public_attribute : Integer;
i_am_another_public_attribute : Integer;
end record;
type car_private is new car_public with record
my_private_attributes : Integer;
end record;
Run Code Online (Sandbox Code Playgroud)
其中car_private在包的私有部分中声明.虽然我觉得这个实现会非常混乱.
人们如何倾向于这样做?
谢谢马特
在Ada中,包的私有部分更接近受保护的C++,而不是私有.大多数情况下,使用私有部分是最好的方法,此外还提供了将单元测试编写为子包的灵活性,以便他们可以测试该类型的属性.
如果您真的想让属性无法访问代码的任何其他部分,则必须在您的身体中定义它们.这可以使用在包的私有部分中声明的不完整类型来完成,然后在正文中完成.然后,您的类型将包含指向此不完整类型的指针,如:
package Foo is
type My_Type is tagged private;
private
type Private_Part;
type Private_Part_Access is access Private_Part;
type My_Type is tagged record
P : Private_Part_Access;
end record;
end Foo;
package body Foo is
type Private_Part is record
...
end record;
end Foo;
Run Code Online (Sandbox Code Playgroud)
这也可以通过使Private_Part成为抽象标记的空记录来完成,并将其扩展到正文中.
当然,这种方案的难点在于内存管理,因为您必须确保您的对象确实释放相应的内存(可能通过使用受控类型).