Dart 2 class with a constructor very similar to th

2019-05-29 13:40发布

问题:

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.

How can I do this with Dart 2?

Thanks!

回答1:

Try this

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);
}