Array/list of objects of different type but with same interface

Ali Çehreli acehreli at yahoo.com
Wed Jun 20 14:14:10 PDT 2012


On 06/20/2012 02:01 PM, Joseph Rushton Wakeling wrote:

 > What I'm puzzling over is how to effectively store the collection of
 > agents. These will be arbitrary in number (and agents might in principle
 > be created or destroyed during the game), will all have the same
 > interface, but will have different implementations -- some may use
 > look-up tables, some may be controlled by neural networks, etc. etc.
 >
 > When I originally wrote this in C, I just used an array of pointers to
 > agents. In C++ I did something similar, defining an agent class of which
 > all implementations were subclasses.
 >
 > I'm just wondering what might be the best and most idiomatic way to do
 > this in D. My likely agent design will be a "policy class" style,
 >
 > struct Agent(alias X, alias Y, ...)
 > {
 > mixin X;
 > mixin Y;
 > // etc...
 > }
 >
 > ... with template mixins to implement the individual components that
 > vary by agent type. The public interface will be identical for all 
agents.
 >
 > What I can't work out is how to store a collection of these agents in an
 > array or similarly efficient container. Can anyone advise?

Sounds like you need an 'interface' and classes that implement it. The 
following code uses simple string mixins:

import std.stdio;

interface Agent
{
     double trade();
}

class SmartAgent : Agent
{
     double trade()
     {
         writeln("Trading smartly");
         return 42;
     }
}

class ConfigurableAgent(string X, string Y) : Agent
{
     mixin(X);
     mixin(Y);

     double trade()
     {
         writefln("Trading with type '%s' and '%s'", typeid(x), typeid(y));
         return x + y;
     }
}

void main()
{
     Agent[] agents;
     agents ~= new SmartAgent();
     agents ~= new ConfigurableAgent!("int x;", "int y;");
     agents ~= new ConfigurableAgent!("double x;", "long y;");

     foreach (agent; agents) {
         agent.trade();
     }
}

Ali



More information about the Digitalmars-d-learn mailing list