Re: Create objects using dynamic class names



"Boefje" <boefje@xxxxxxxxxxx> wrote in message
news:1155285374.570852.177570@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

The subject might be an incorrect description of what I want. What I
want is quite simple.

I have got a part of code whic looks like this:

lFrame := TFrameStap1.Create(PanelMidden, 1);
FFrameStappen.Add(lFrame);
lFrame := TFrameStap2.Create(PanelMidden, 2);
FFrameStappen.Add(lFrame);
lFrame := TFrameStap3.Create(PanelMidden, 3);
FFrameStappen.Add(lFrame);
lFrame := TFrameStap4.Create(PanelMidden, 4);
FFrameStappen.Add(lFrame);
lFrame := TFrameStap5.Create(PanelMidden, 5);
FFrameStappen.Add(lFrame);

Because I keep repeating myself, I would do this in some kind of loop.

for i:= 0 to MAXFRAMES - 1 do
begin
lFrame := XXXXXXXXXXXXXXX.Create(PanelMidden, i);
FFrameStappen.Add(lFrame);
end;

With what should I replace XXXXXXXXXXXXXXX? If it is possible, I guess
I have to do something with ClassName. Is it possible?

Yes. There are at least three different ways, and more variants that
may qualify as different depending on how you look at it.

The most literal solution is to use GetClass or FindClass. The help
file knows.

But that's not the best solution. A more elegant solution to your
current problem could be to derive your TFrameStapX classes from
a common base class and have an array of class references to the
individual classes. Usually, this requires a virtual constructor so
you can use 'the same' constructor each time, yet end up executing
code that is appropriate to the current subclass.

This replaces the repetition of code with a table and a loop. You
still have to hardcode the table. That's a common pattern.

But your code looks suspicious. It has the same running number in
_two_ places. Doesn't TFrameStap4 already know that it's number 4?
Logic dictates that you could either do without the final parameter,
or merge the five classes into one.

Groetjes,
Maarten Wiltink


.