【问题标题】:Is there a way to "code reuse" classes that are only exposed the implementation section?有没有办法“代码重用”只公开实现部分的类?
【发布时间】:2017-09-23 18:00:49
【问题描述】:

我刚刚阅读了一种有趣的代码结构化方法,该方法将实际类隐藏在单元的实现部分深处,并仅通过接口公开它们,如下所示:

unit MyClass;

interface

type

   IMyClass = interface(IInterface)
   [GUID]
      procedure A;
      procedure B;
   end;

function CreateMyClass: IMyClass;

implementation

type

   TMyClass = class(TInterfaceObject, IMyClass)
   strict private    
      procedure A;
      procedure B;
   end;

function CreateMyClass: IMyClass;
begin
   Result := TMyClass.Create;
end;

   ...

end;

在我需要从 TMyClass 继承一个类以进行代码重用之前,这会产生奇迹。除了在同一单元implementation 部分中插入第二个类之外,还有其他方法吗?

【问题讨论】:

  • 类本身在其他任何地方都不可见,除了在该单元内,在它声明的位置下方。您希望如何以不同的方式做到这一点?

标签: delphi inheritance


【解决方案1】:

您可以从类继承的唯一方法是在可以看到类声明的代码中。因此,如果声明仅出现在实现部分中,则只有也在该实现部分中的代码可以从该类派生。

【讨论】:

  • 那么,在Delphi中没有办法隐藏构造方法,同时从另一个单元继承这个隐藏的类?
  • 您可以将构造函数设为私有。
  • 但是这种方式不能覆盖TObject公共构造函数
  • 那句话对我来说没有任何意义
  • 我的意思是,如果我将类构造函数设为私有,我仍然可以使用 TObject public "Create" 构造函数调用它
猜你喜欢
  • 2020-03-07
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2021-12-18
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多