声明一个普通的类

//声明类
class Person {
  //类的属性
  String name = '张三';

  void getInfo() {
    print('我是 $name');
  }

  //Dart 中所有的东西都是对象;
}

void main(List<String> args) {
  Person p = new Person();
  p.getInfo();

  p.name = '测试';
  p.getInfo();
}

命名构造函数

class Point {
  num x, y;

  //申明普通构造函数
  Point() {
    this.x = 0;
    this.y = 10; //  dart中 this可以省略
    print(this.x);
    print(this.y);
  }

  //命名构造函数
  Point.origin() {
    x = 0;
    y = 0;
  }

  //通过一个JSON构造函数默认参数
  Point.fromJson({x: 10, y: 5});
}

void main(List<String> args) {
  var p = new Point.fromJson(x: 10, y: 5);
  print(p.x);
}

常量构造函数

常量构造函数写法如下:

class ImmutablePoint {
   final x;
   final y;
   
   const ImmutablePoint(this.x, this.y);
}

常量构造函数不能有函数体

工厂构造函数

class Person {
  String name;

  static Person instance;

  //工厂构造函数
  factory Person([String name = '刘备']) {
    //工厂构造函数中不能使用this关键字
    if (Person.instance == null) {
      // 第一次实例化
      Person.instance = Person.newSelf(name);
    }


    //第二次声明的时候修改name,但是还是使用的上一次声明的实例
    Person.instance.name = name;

    return Person.instance;
  }

  Person.newSelf(this.name);
}

void main(List<String> args) {
  Person p1 = Person('name');
  print(p1.name);
  Person p2 = Person('name2');
  print(p2.name);

  print(p1 == p2);
}

标签: none

添加新评论