首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Delphi中重用同一个作用域上的同一个TInterfacedObject实例

如何在Delphi中重用同一个作用域上的同一个TInterfacedObject实例
EN

Stack Overflow用户
提问于 2020-06-12 15:20:26
回答 1查看 92关注 0票数 1

我已经实现了一个位图适配器来扩展位图功能,如下所示:

代码语言:javascript
复制
unit UBitmapHelper;

IBmpUtils = interface
  procedure SomeNewRoutine;
end;

TBitmapUtilsAdapter = class (TInterfacedObject, IBmpUtils)
public
  constructor Create (ABitmap: TBitmap);
  //IBmpUtils
  procedure SomeNewRoutine;
end;

TBitmapHelper = class helper for TBitmap
  function Utils: IBmpUtils; //method factory pattern
end;

function TBitmapHelper.Utils: IBmpUtils;
begin
  Result := TBitmapUtilsAdapter.Create(Self);
end;

因此,我现在可以如下所示地使用这个适配器:

代码语言:javascript
复制
uses UBitmapHelper;

procedure Test;  
var
  MyBitmap: TBitmap;
  i: Integer;
begin
  MyBitmap := TBitmap.Create;
  MyBitmap.SetSize(50, 50);
  for i := 1 to 100 do
    MyBitmap.Utils.SomeNewRoutine;
  FreeAndNil(MyBitmap);  
end;

我不需要释放Utils作为我从TInterfacedObject继承的适配器,所以它将自动释放时,外出测试过程范围,很好!但也许有一点性能问题。

编译器是否为每次迭代创建了一个新的Utils实例,或者在这种情况下,它足够聪明地重用相同的Utils实例,而它位于相同的作用域?

显然,我可以在for-循环之前得到实例,然后在内部使用它,但是我正在试图找出如何在不影响性能的情况下在任何地方使用表示法MyBitmap.Utils.SomeNewRoutine。是做这件事的方法吗?

注:我使用的是Delphi 10.3

编辑

更清楚的是:

  1. 我被强制实现IBmpUtils接口,所以我不能使用记录类和助手类。我还被迫不要创建自己的TBitmap子类,然后实现IBmpUtils接口,所以我唯一的解决方案是适配器。

是否有任何方法可以做到这一点,而不像上面描述的那样造成性能损失(即在循环中使用表示法)?

EN

回答 1

Stack Overflow用户

发布于 2020-06-12 16:27:15

在注释中,主要目标是能够为每个bm.Utils.SomeProcAbm编写类似TBitmapbm.Utils.SomeProcB之类的东西,并且尽可能少的开销(性能损失)。我的第一个想法是尝试

代码语言:javascript
复制
type
  TBitmapUtils = record
  private
    FBitmap: TBitmap;
  public
    procedure MyProc1;
    procedure MyProc2;
  end;

  TBitmapHelper = class helper for TBitmap
    function Utils: TBitmapUtils; inline;
  end;

哪里

代码语言:javascript
复制
{ TBitmapUtils }

procedure TBitmapUtils.MyProc1;
begin
  ShowMessageFmt('The width of the bitmap is %d.', [FBitmap.Width]);
end;

procedure TBitmapUtils.MyProc2;
begin
  ShowMessageFmt('The height of the bitmap is %d.', [FBitmap.Height]);
end;

{ TBitmapHelper }

function TBitmapHelper.Utils: TBitmapUtils;
begin
  Result.FBitmap := Self;
end;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62347295

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档