Dart 2类的构造函数与其他语言的多态性非常相似 [英] Dart 2 class with a constructor very similar to the polymorphism of other languages
本文介绍了Dart 2类的构造函数与其他语言的多态性非常相似的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用 Dart 2 类来代表一张照片.照片可以是矩形或圆形.因此,通过多态性,我可以编写:
I need to represent a photo with a Dart 2 class. The photo can be rectangular or circular. So, with a polymorphism I could write:
import 'dart:math';
class Photo {
double width;
double height;
double radius;
double area;
Photo(double width, double height) {
this.width = width;
this.height = height;
this.area = width * height;
}
Photo(double radius) {
this.radius = radius;
this.area = pi * pow(radius, 2);
}
}
因此,我可以创建具有半径的照片或具有宽度和高度的照片; 没有其他选择 .
So I could allow to create a Photo with radius or a Photo with width and height; no other option.
我该如何使用 Dart 2 ?
谢谢!
推荐答案
尝试一下
import 'dart:math';
class Photo {
final double area;
// This constructor is library-private. So no other code can extend
// from this class.
Photo._(this.area);
// These factories aren't needed – but might be nice
factory Photo.rect(double width, double height) => new RectPhoto(width, height);
factory Photo.circle(double radius) => new CirclePhoto(radius);
}
class CirclePhoto extends Photo {
final double radius;
CirclePhoto(this.radius) : super._(pi * pow(radius, 2));
}
class RectPhoto extends Photo {
final double width, height;
RectPhoto(this.width, this.height): super._(width * height);
}
这篇关于Dart 2类的构造函数与其他语言的多态性非常相似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文