Context
Trying to have a generic "Observer" pattern in Delphi, I managed to make something working:
TObserver = class
protected
FSubject: TSubject;
public
constructor Create(); virtual; overload;
constructor Create( constref subject: TSubject ); virtual; overload;
destructor Destroy(); virtual;
procedure ReAttach( constref newSubject: TSubject ); virtual;
procedure Update(constref subject: TSubject); virtual;
end;
TSubject = class
protected
FObservers: TList<TObserver>;
public
constructor Create; overload;
destructor Destroy; override;
procedure Notify(); virtual;
procedure Attach(constref AObserver: TObserver); virtual;
procedure Detach(constref AObserver: TObserver); virtual;
end;
Every new Callback signature require to extend both the TSubject and TObserver. This quickly become tedious.
TMyObserver = class( TObserver )
public
type TCallback = procedure (...) of object;
private
FCallback: TCallback;
public
property Callback: TCallback read FCallback write FCallback;
procedure Update(constref subject: TSubject, ...); overload;
end;
TMySubject = class( TSubject )
...
This is not practical, so I wonder if there is a better approach.
For example, in C++, there are what are called Variadic Templates
which would probably be called somehow Variadic Generics
in Delphi?
#include <iostream>
#include <functional>
template <typename ...UpdateArgs>
class Observer
{
public:
using CallbackType = std::function<void(UpdateArgs...)>;
CallbackType callback;
void Update(UpdateArgs... args)
{
if (callback) callback(args...);
}
};
int main()
{
Observer<int, const std::string&> obs1;
obs1.callback = [](int vInt, const std::string& vStr)
{
std::cout << "Int is: " << vInt << " and String is: '" << vStr << "'" << std::endl;
};
obs1.Update(42, "Hi you");
// OR
Observer<float> obs2;
obs2.callback = [](float f)
{
std::cout << "Float is: " << f << std::endl;
};
obs2.Update(3.1415926);
return 0;
}
For those not very fluent with C++, this basically is a generic Observer
with a variable number of arguments. Making the callback available for the exact types and number of arguments required.
Question
Does Delphi have Variadic Generics? that is, a way of specifying a variable set of arguments, allowing to specialize TObserver
and TSubject
for each required notification signature.
I would like the solution to be type-safe.
Otherwise, what are the alternatives?