Automatically execute a method before other methods in Delphi with RAD XE

Good afternoon,

I am coding some TFoo and TBar . They have several methods that require calling the swithcing function TFoo.switch and TBar.switch .

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

This superclass has an FNumConfig private field that describes the number of PCI cards. The Switch method uses a function from some library:

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

I would like to ask you if there is a way to call the Switch super function before doing any DoSomethingWithFoo() or DoSomethingWithBar() respectfully? I mean something like this

 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; 

And the TBar class

 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; 

I know about a simple method:

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

but I would like to write all this in one place - in the declaration of classes.

+1
source share
2 answers

Delphi does not support anything like this built-in. What you are asking for is essentially an aspect-oriented programming function. There are several third party options that have been discussed here before .

+1
source

There are some object-oriented design patterns that can be useful to solve this problem:

  • Command line
  • Decorator drawing
  • Strategy Template

This means: operations can be implemented as β€œCommand” objects, which, if necessary, are issued by the β€œSwitcher” class.

0
source

All Articles