我了解到接口是一种良好的方法来解耦代码。Nick Hodges在此方面写了一章节,阅读后我编写了以下代码:
//interfaces
type
ILocalization = interface
['{1D144BCE-7D79-4672-8FB5-235422F712EE}']
function localize(const aWordId: string): string;
end;
type
IActions = interface
['{31E8B24F-0B17-41BC-A9E4-F93A8E7F6ECF}']
procedure addWord(const aIndex, aWord: string);
procedure removeWord(const aIndex: string);
end;
//implementation
type
TLocalization = class sealed (TInterfacedObject, ILocalization, IActions)
private
FTranslationList: TDictionary<string, string>;
public
constructor Create;
destructor Destroy; override;
//interface implementations
function localize(const aWordId: string): string;
procedure addWord(const aIndex, aWord: string);
procedure removeWord(const aIndex: string);
end;
我计划使用这个类来本地化(翻译)我的Delphi安卓应用程序。
当我要创建一个该类的实例时,我会执行以下操作。
var
Italiano: TLocalization;
begin
Italiano := TLocalization.Create;
end;
既然 TLocalization
应该已经继承了 AddRef 和 Release 方法,所以我不会在 finally 中使用它们,但如果 Italiano 是一个类类型而不是接口类型,这是否仍然发生?
我的意思是:
- Italiano: TLocalization -> 在这里我可以使用所有的方法
- Italiano: ILocalization -> 在这里我只能使用 localize 函数
考虑到(如我之前所说),TLocalization 继承 AddRef 和 Release 方法,如果我理解正确,我就不需要释放它。尽管如此,对于 ILocalization,它还有其他好处吗?我不明白以上两种情况的区别是什么。
var Actions: IActions; .... Actions := Italiano as IActions;
。现在您有了两个接口变量,它们背后是同一个单一对象,该对象现在的引用计数为2。 - David Heffernan