Inheritance of TCollectionItem

Posted by JamesB on Stack Overflow See other posts from Stack Overflow or by JamesB
Published on 2010-03-15T12:18:28Z Indexed on 2010/03/15 12:19 UTC
Read the original article Hit count: 208

I'm planning to have collection of items stored in a TCollection.

Each item will derive from TBaseItem which in turn derives from TCollectionItem,

With this in mind the Collection will return TBaseItem when an item is requested.

Now each TBaseItem will have a Calculate function, in the the TBaseItem this will just return an internal variable, but in each of the derivations of TBaseItem the Calculate function requires a different set of parameters.

The Collection will have a Calculate All function which iterates through the collection items and calls each Calculate function, obviously it would need to pass the correct parameters to each function

I can think of three ways of doing this:

  1. Create a virtual/abstract method for each calculate function in the base class and override it in the derrived class, This would mean no type casting was required when using the object but it would also mean I have to create lots of virtual methods and have a large if...else statement detecting the type and calling the correct "calculate" method, it also means that calling the calculate method is prone to error as you would have to know when writing the code which one to call for which type with the correct parameters to avoid an Error/EAbstractError.

  2. Create a record structure with all the possible parameters in and use this as the parameter for the "calculate" function. This has the added benefit of passing this to the "calculate all" function as it can contain all the parameters required and avoid a potentially very long parameter list.

  3. Just type casting the TBaseItem to access the correct calculate method. This would tidy up the TBaseItem quite alot compared to the first method.

What would be the best way to handle this collection?

© Stack Overflow or respective owner

Related posts about delphi

Related posts about inheritance