Dart 入门-2

2018/11/17 Dart

概述

可选参数

import 'dart:math';

class Rectangle {
  int width;
  int height;
  Point origin;

//   Rectangle(this.width, this.height, this.origin);

  // 构造方法使用了可选类型参数
  //this.origin = const Point(0, 0) 这样的代码表明给实例变量 origin 提供了默认的值 Point(0,0),默认值必须是在编译器就可以确定的常量。

  //this.origin, this.width 和 this.height 嵌套在闭合的花括号中 ({}) ,用来表示它们是可选的命名参数。

  //this.origin, this.width 和 this.height 使用了 Dart 提供的简便方法来直接对类中的实例变量进行赋值。

  Rectangle({this.origin = const Point(0, 0), this.width = 0, this.height = 0});

  @override
  String toString() => 'Origin: (${origin.x}, ${origin.y}), width: $width, height: $height';
}

main() {
  print(Rectangle(origin: const Point(10, 20), width: 100, height: 200));
  print(Rectangle(origin: const Point(10, 10)));
  print(Rectangle(width: 200));
  print(Rectangle());
} // Included main() to suppress uncaught exception.

创建工厂模式

//初始类
import 'dart:math';

abstract class Shape {
  num get area;
}

class Circle implements Shape {
  final num radius;
  Circle(this.radius);
  num get area => pi * pow(radius, 2);
}

class Square implements Shape {
  final num side;
  Square(this.side);
  num get area => pow(side, 2);
}

main() {
  final circle = Circle(2);
  final square = Square(2);
  print(circle.area);
  print(square.area);
}

工厂模式

import 'dart:math';

abstract class Shape {
  num get area;
}

class Circle implements Shape {
  final num radius;
  Circle(this.radius);
  num get area => pi * pow(radius, 2);
}

class Square implements Shape {
  final num side;
  Square(this.side);
  num get area => pow(side, 2);
}

Shape shapeFactory(String type) {
  if (type == 'circle') return Circle(10);
  if (type == 'square') return Square(2);
  throw 'Can\'t create $type.';
}

main() {
  Shape sharpeCircle = shapeFactory('circle');
  Shape sharpeSquare = shapeFactory('square');
  print(sharpeCircle.area);
  print(sharpeSquare.area);

}

接口

Dart 语言并没有提供 interface 关键字,但是每一个类都隐式地定义了一个接口。

函数式

String scream(int length) => "A${'a' * length}h!";

main() {
  final values = [1, 2, 3, 5, 10, 50];
  for (var length in values) {
    print(scream(length));
  }
  print('===========================');
  values.map(scream).forEach(print);

  //dart:collection 库中的 List 和 Iterable 支持 fold, where, join, skip 等函数式方法,另外 Dart 还支持 Map 和 Set 类型。
   print('===========================');
  values.skip(1).take(3).map(scream).forEach(print);
}

Search

    Table of Contents