Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dart - Extending a class with only one factory constructor

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...