dynamic instantiation from a network message

141 views
Skip to first unread message

Ron Pastore

unread,
Jul 20, 2012, 8:16:21 PM7/20/12
to mi...@dartlang.org
Hi,
Dart looks really great!  Thanks for the new and exciting tool.  I'm still scratching the surface and have an idea I'd like to try. I'm hoping to get some feedback, pointers, etc..  Was thinking dart may be capable of something like this already but haven't found...

I'm trying to build a command chain implementation where commands within a chain can run on the server via vm, on the client, or be indifferent to where they run.

I'm planning to use web sockets to assist in dispatching commands to the correct tier, and passing json along to help commands be context aware.

Right now i'm looking for a good way to dynamically instantiate command objects.  Also, because a command can be far down in a chain, but have its execution be the first in a particular environment, the command and chain will need to be instantiated from something that can be sent over the network.

Instantiation from a stringified class name or some type of command object marshalling would be perfect, haven't found any examples though, does dart support something like this?  Any suggestions/time savers would be appreciated. Thanks again!

Justin Fagnani

unread,
Jul 20, 2012, 8:38:36 PM7/20/12
to Ron Pastore, mi...@dartlang.org
So far I've been using a simple factory pattern for this. Assuming all your JSON objects have some kind or type field you can look up a factory / deserializer in a map:

typedef Object Factory(Map map);
Map<String, Factory> getFactories() => {
  "foo": (m) => new Foo.fromMap(m),
  "bar": (m) => new Bar.fromMap(m),
}

Object create(String json) {
  var map = JSON.parse(json);
  Factory factory = getFactories()[map["type"]];
  return factory(map);
}

There's some working code here, also for a command library:

Hope that helps,
  Justin

Seth Ladd

unread,
Jul 21, 2012, 12:44:46 PM7/21/12
to Justin Fagnani, Ron Pastore, mi...@dartlang.org
Hi Ron,

Thanks for the question! This will become possible when we ship our Mirrors API. Mirrors aren't fully speced or implemented, which is why you haven't seen any samples. :) For now, try Justin's technique and let us know.

Thanks,
Seth

Ron

unread,
Jul 21, 2012, 1:01:32 PM7/21/12
to Seth Ladd, Justin Fagnani, mi...@dartlang.org
Awesome, thanks guys, will do. 

Sent from my iPhone
Reply all
Reply to author
Forward
0 new messages