Extending a class with only one factory constructo

2019-01-19 19:33发布

问题:

I was wondering which is the best way to extend the CustomEvent class, a class which has only one factory constructor. I tried doing the following and ran into an issue with the super constructor :

class MyExtendedEvent extends CustomEvent {
  int count;

  factory MyExtendedEvent(num count) {
    return new MyExtendedEvent._internal(1);
  }

  MyExtendedEvent._internal(num count) {
    this.count = count;
  }
}

but I can't get it working. I always run into :

unresolved implicit call to super constructor 'CustomEvent()'

If i try chaning the internal constructor to :

MyExtendedEvent._internal(num count) : super('MyCustomEvent') {
  this.count = count;
}

I end up with :

'resolved implicit call to super constructor 'CustomEvent()''.

I'm not sure what I'm doing wrong - but I guess the problem is that the CustomEvent has only one constructor which is a factory constructor (as doc says - http://api.dartlang.org/docs/releases/latest/dart_html/CustomEvent.html)

What is the best way to extend a CustomEvent, or any class of this form?

回答1:

You can't directly extend a class with a factory constructor. However you can implement the class and use delegation to simulate the extension.

For instance :

class MyExtendedEvent implements CustomEvent {
  int count;
  final CustomEvent _delegate;

  MyExtendedEvent(this.count, String type) :
    _delegate = new CustomEvent(type);

  noSuchMethod(Invocation invocation) =>
      reflect(_delegate).delegate(invocation);
}

NB : I used reflection here to simplify the code snippet. A better implementation (in regard of performances) would have been to define all methods like method1 => _delegate.method1()



回答2:

Unfortunately, you can't extend a class if it only has factory constructors, you can only implement it. That won't work well with CustomEvent though since it's a DOM type, which is also why it only has factory constructors: the browser has to produce these instances, the Dart object is just a wrapper. If you try to implement CustomElement and fire one, you'll probably get an error.



标签: dart