扩建工厂

时间:2013-07-08 20:20:52

标签: design-patterns dart

我有两个班级

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类的子类型。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分: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);
}