我有两节课
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类的子类型。有什么方法可以实现?
最佳答案
您必须通过实现所有方法或使用A
来实现noSuchMethod(invocation)
和委托(delegate)方法调用。
对于给定的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);
}
关于design-patterns - 扩建工厂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17535308/