当我们在Delphi中设计一个类时,通常我们有私有字段(成员),私有setter和getter方法以及公共属性。从课外,只有公共财产才能访问这些数据;该类的用户甚至不知道存在getter方法。它是否违反了接口属性访问器的公共封装?
所以getter和setter方法封装的实例成员和财产封装了getter和setter方法。
然而,定义一个接口,当我们揭露那些方法:
ICounter = interface
// I wouldn't want to specify these 2 methods in the interface, but I'm forced to
function GetCount: Integer;
procedure SetCount(Value: Integer);
property Count: Integer read GetCount write SetCount;
end;
实施具体类:
TCounter = class(TInterfacedObject, ICounter)
private
function GetCount: Integer;
procedure SetCount(Value: Integer);
public
property Count: Integer read GetCount write SetCount;
end
使用它:
var
Counter: ICounter;
begin
Counter := TCounter.Create;
Counter.Count := 0; // Ok, that's my public property
// The access should me made by the property, not by these methods
Counter.SetCount(Counter.GetCount + 1);
end;
如果属性封装getter/setter私有方法,是不是违规? getter和setter是具体类的内部,并且不会被暴露。
这听起来像一个咆哮。你的问题是什么? –
哪一点让你感到困惑?这对我来说很有意义。 –
-1在您已经有三个答案后完全改变问题的性质。我反对你的发言,我的修改“改变了方向”。我的编辑把你的两个问题放在标题中,这样标题就成了一个恰当的问题。 *你的*是改变方向的编辑。 –