使用 RAD XE 在德尔福中自动执行一个方法,然后再执行另一个方法



美好的一天,

我编写了一些类TFooTBar。他们有一些方法需要调用 swithcing 函数TFoo.switchTBar.switch

TBaseFooBar = class
  strict private
    FNumConfig: Word;
  protected
    procedure Switch;  
end;

这个超类有一个私人字段FNumConfig,用于描述PCI卡的数量。Switch方法使用来自某个库的函数:

procedure TBaseFooBar.Switch;  
begin
  tmkselect(FNumConfig);
end;

我想问你有没有办法在执行任何DoSomethingWithFoo()DoSomethingWithBar()之前调用超级函数Switch?我的意思是这样的事情

TFoo = class(TBaseFooBar )
  { FNumConfig: Word; // this number declares the number of a PCI card}
  public 
  @Switch // before this method
  procedure DoSomethingWithFoo1();
// ...
  @Switch // and before this one
  procedure DoSomethingWithFooN();
// before this one there is no calling of Switch
  function NotSwitching();
end;

TBar

TBar = class(TBaseFooBar )
{  FNumConfig: Word; // this is another one number declares of another PCI card, they are not equal. }
public 
@Switch // before this method
  procedure DoSomethingWithBar1();
// ...
@Switch // and before this one
  procedure DoSomethingWithBarN();
end;

我知道一个简单的方法:

procedure TFoo.DoSomethingWithFoo1();  
begin
Switch();
// and another stuff.
end;

但我想把所有这些都写在一个地方——在类的声明中。

Delphi不支持内置的类似内容。你所要求的本质上是一个面向方面的编程功能。第三方供应商提供了一些选项,之前已经在这里讨论过。

有一些面向对象的设计模式可能有助于解决这个问题:

  • 命令模式
  • 装饰器图案
  • 策略模式

这意味着:操作可以作为"Command"对象实现,在需要时由"切换器"类装饰。

最新更新