While working on an internal project I came into a situation where a user (that is, a fellow programmer) would have to create a hierarchy of classes. As it turned out, this hierarchy would contain almost no implementation, just the class declarations, with one exceptions – every class would still have to be responsible for creating its children objects. Then I had a thought. Maybe I could use attributes and RTTI to do that in one central place instead of in every object.
Sunday, October 28, 2012
Thursday, December 15, 2011
Creating an Object from an Unconstrained Generic Class
As you know if you follow my blog, OmniThreadLibrary now offers a simple way to do optimistic and pessimistic atomic initialization which works for interfaces, objects and (in the case of the pessimistic initialization), anything else. [In case you missed those articles - I also discussed a comparison of both methods and wrote a short post about the third approach to initialization.]
A typical usage of both types of initialization would be:
var sl: TStringList; ol: Locked<TObjectList>; Atomic<TStringList>.Initialize(sl, function: TStringList begin Result := TStringList.Create; end); ol.Initialize( function: TObjectList begin Result := TObjectList.Create; end);
As you can see, this is pretty long-winded. If you are initializing an interface, then you’ll usually have written a factory method already and the code would be much simpler (example below this paragraph) but in the case of objects this is not very typical.
Atomic<IGpIntegerList>.Initialize(list, TGpIntegerList.CreateInterface);
So I thought – both Atomic and Locked already know what entity type they wrap around so calling a constructor from inside Initialize would be trivial, eh? I could then write a simplified version
Atomic<TStringList>.Initialize(sl); ol.Initialize;
and use the longer version only when needed, for example to initialize interfaces or to call a non-default object constructor. What could possibly go wrong?