First Steps: Dynamic class instantiation

Kevin Bealer kevinbealer at gmail.com
Sun Jan 28 03:40:06 PST 2007


Thomas wrote:
> Hi
> 
> I'm just making my first steps to understand D, and sometimes I'm a little bit offroad as I do not know C/C++, just PHP, Javascript etc.
> 
> I would like to write a small shell application with a small bundle of functionalities. As a first step, the user must choose which function to use (I already got that part). Than she must enter some information for the function to work on.
> 
> I thought of doing this by creating classes for each functionality implementing the same interface and creating an array in main() that somehow refers to these classes. There the trouble starts.
> 
> I don't know how to create such an array, and of which type it has to be. To be more specific, I provide you with a PHP example of what I want to do:
> 
> $selected = 1;
> $classes = array('class1','class2');
> $className = $classes[$selected];
> $object = new $className;
> 
> Thanks for any help.
> 
> Thomas

(This probably goes in D.learn by the way.)

If you have a class that follows a common interface (I'll call it 
Command) you could do this:

class Command {
     static Command[char[]] actions;

     this(char[] name)
     {
          actions[name] = this;
     }

     static void run(char[] name, char[] arguments)
     {
         assert(name in actions);
         actions[name].work(arguments);
     }

     abstract void work(char[] arguments);
};

Then you can create instance of Command:

class Rename : Command {
     this()
     {
         super("rename");
     }

     void work(char[] arguments)
     {
         // do a rename or something
     }
};

If you create one object of each subclass:

Rename r = new Rename;

The calling code could do this:

Command.run("rename", "a b");

Which would run the Rename.work() command.

Kevin



More information about the Digitalmars-d mailing list