参数如何传递到ClassMirror.newInstance(...)的参数列表中?

时间:2015-11-06 08:04:32

标签: dart factory-pattern dart-mirrors

我编写了以下(工作)代码,现在想添加一个" octave"对于Animal子类的构造函数调用的参数,我想这样当创建一个新动物时,工作室可以进行适当的调整。或者其他的东西。它只是一种弄清楚这些Dart语言语义的方法。

(无疑是愚蠢但很有趣,是吗?)的想法是,AnimalStudio实例根据它是什么样的AnimalStudio知道要添加什么样的Animal。因此CatStudio自动添加Cat。 AnimalStudio对CatStudio或Cat一无所知,因此它可以成为公共API的一部分,在野外扩展#34;

每个工作室只有一只动物可以阻止反馈。

有三个文件: 动物 2. model.dart 3. main.dart

file:animals.dart

import "dart:mirrors";

abstract class AnimalStudio {
  Animal animal;
  final String animalType;

  String record() {
    print("$animalType: ${animal.sing()} in ${animal.octave}");
  }

  AnimalStudio(octave) {
    animal = new Animal(animalType, octave);
//    print("AnimalStudio::setup(): ${animal.toString()}: $animalType");
//    print("AnimalStudio::makeSound: " + animal.makeSound());
  }
}

/* Here's the magic factory.
 * To do:
 *  Get "cat", "dog", etc from mirror system.
 */
abstract class Animal {
  factory Animal(String type, String octave) {
    MirrorSystem libs = currentMirrorSystem();
    LibraryMirror lib = libs.findLibrary(new Symbol('app.models'));
    Map<Symbol, Mirror> classes = lib.declarations;
    // To do: handle exception if class not found
    ClassMirror cls = classes[new Symbol(type)];
    InstanceMirror inst = cls.newInstance(new Symbol(''), [octave]);
    return inst.reflectee;
  }
}

class AnimalBase implements Animal {
  final String sound; // the sound she makes when she sings
  String sing() => sound;
  AnimalBase(this.sound);
}

file:model.dart

library app.models;

import 'animals.dart';

class CatStudio extends AnimalStudio {
  final animalType = "Cat";
  CatStudio(octave) : super(octave);
}

class Cat extends AnimalBase {
  final String octave;
  Cat(this.octave) : super("Meow");
}

file:main.dart

import "model.dart";

void main() {
  new CatStudio("C major").record();
}

0 个答案:

没有答案