3

我有两节课

class A {
    String _id;

    static final Map<String, A> _instances = <String, A>{};

    factory A.getInstance(String id){            
        if(!_instances.containsKey(id)){
            _instances[id] = new A._internal(id);
        }
        return _instances[id];            
    }    

    A._internal(this._id);
}

class B extends A {
    factory B.getInstance(int id){
        return new A.getInstance(id.toString());
    }
}

我知道这不是一个好习惯,因为 A 类不是 B 类的子类型。有没有办法做到这一点?

4

1 回答 1

2

您必须通过实现 A所有方法或使用noSuchMethod(invocation).

对于给定的A类:

class A {
  static final Map<String, A> _instances = <String, A>{};

  String _id;

  A._internal(this._id);
  factory A.getInstance(String id) =>
      _instances.putIfAbsent(id, () => new A._internal(id));

  String get id => _id;
  String get name => "name_${_id}";
}

您的B课程可能如下所示:

class B implements A {
  final A a;

  B(int id) : a = new A.getInstance(id.toString());

  String get id => a.id;
  String get name => a.name;
}

或与noSuchMethod

import 'dart:mirrors';
class B implements A {
  final A a;

  B(int id) : a = new A.getInstance(id.toString());

  noSuchMethod(Invocation invocation) => reflect(a).delegate(invocation);
}
于 2013-07-08T20:45:38.170 回答