手记

【Dart 专题】Factory 工厂构造函数

      小菜学习 Flutter 有一段时间,虽可以应用基本的 Dart 语法,但对于一些特殊的语法还是很陌生,小菜准备开一个小的【Dart 专题】记录一些日常用的 Dart 语法及相关应用;

Constructors

      Constructors 构造方法在日常应用中必不可少,小菜是 Android 开发,对 Java 构造函数更加熟悉;

      Constructors 构造方法是对象的初始化;函数名与类名一致且没有返回值类型;默认是无参构造函数,可以通过重载方式设置多个函数名相同的构造函数;

      而 Dart 构造函数与 Java 略有不同,小菜简单尝试;

构造函数类型

      Dart 构造函数主要分为四类,分别是 Default Constructors 默认构造函数、Named Constructors 命名构造函数、Constant Constructors 常量构造函数和 Factory Constructors 工厂构造函数;

Default Constructors

      默认构造函数与 Java 类似,可以是无参构造函数和有参构造函数;但与 Java 不同的是,Dart 构造函数不允许重载,即不允许有相同名称的构造函数;

无参构造函数

      如果不声明构造函数,则会提供默认无参构造函数;

class People {
  People() {
    print('Dart --> People()');
  }
}
有参构造函数

      Dart 还提供了简易的语法糖的方式优化代码格式;

class People {
  String name;
  int age, sex;

  /// 不可与无参构造函数同时出现
  People(name, age, {sex}) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    print('Dart --> People($name, $age, {$sex})');
  }
  
  /// 简易语法糖
  People(this.name, this.age, {this.sex});
}

      当子类继承父类时,初始化子类构造函数会优先初始化父类构造函数;继承时需要使用 super() 父类构造函数,若父类为无参构造函数时可以省略;

class Student extends People {
  Student(name, age, {sex}) : super() {
    this.name = name;
    this.age = age;
    this.sex = sex;
    print('Dart --> Student($name, $age, {$sex}) extends People()');
  }
}
People people = People();
print('<---------------->');
Student student = Student('阿策小和尚', 100, sex: 0);

Named Constructors

      使用命名构造函数可以为实现多个构造函数或提供更清晰的构造函数;同时子类需要实现 super() 构造函数类型完全取决于父类构造函数类型;其中命名构造函数是不允许被继承的,若子类需要实现与父类同名的命名构造函数,则需要调用父类的同名的命名构造函数;

People.fromMap(map) {
  this.name = map['name'];
  this.age = map['age'];
  this.sex = map['sex'];
  print('Dart --> People.fromMap($map) --> $name, $age, $sex');
}

Student.fromMap(map) : super.fromMap(map) {
  this.name = map['name'];
  this.age = map['age'];
  this.sex = map['sex'];
  print('Dart --> Student.fromMap($map) extends People() --> $name,$age,$sex');
}

Map map = {'name': '阿策小和尚', 'age': 100, 'sex': 0};
People people = People.fromMap(map);
print('<---------------->');
Student student = Student.fromMap(map);

Constant Constructors

      如果生成类的对象是不会变的,可以定义常量构造函数;

  1. 其中所有实例变量都是 final 类型的,类中不允许有普通变量类型,因此其变量在构造函数完成之后不允许变更;
  2. 变量中不允许有初始值;
  3. 常量构造函数必须用 const 关键词修饰;
  4. 常量构造函数不允许有函数体;
  5. 实例化时需要加 const 否则实例化的对象仍然可以修改变量值;
class People {
  final String name ;
  final int age ;
  final int sex;
  const People(this.name, this.age, {this.sex});
}

class Student extends People {
  Student(name, age, {sex}) : super(name, age, sex: sex){
    print('Dart --> Student($name, $age, {$sex}) extends People() --> $name, $age, $sex');
  }
}

const People people = People('阿策小和尚', 100, sex: 0);
print('People.name=${people.name}, age=${people.age}, sex=${people.sex}');
print('<---------------->');
Student student = Student('阿策小和尚', 100, sex: 0);
print('Student.name=${student.name}, age=${student.age}, sex=${student.sex}');

Factory Constructors

      工厂构造函数不需要每次构建新的实例,且不会自动生成实例,而是通过代码来决定返回的实例对象;工厂构造函数类似于 static 静态成员,无法访问 this 指针;一般需要依赖其他类型构造函数;工厂构造函数还可以实现单例;

class People {
  String name;
  int age, sex;
  static People _cache;

  People() {
    print('Dart --> People()');
  }

  People.fromMap(map) {
    this.name = map['name'];
    this.age = map['age'];
    this.sex = map['sex'];
    print('Dart --> People.fromMap($map) --> $name, $age, $sex');
  }

  factory People.map(map) {
    if (People._cache == null) {
      People._cache = new People.fromMap(map);
      print('Dart --> People.map($map) --> ${map['name']}, ${map['age']}, ${map['sex']} --> People._cache == null');
    }
    print('Dart --> People.map($map) --> ${map['name']}, ${map['age']}, ${map['sex']}');
    return People._cache;
  }

  factory People.fromJson(json) => People();
}

Map map = {'name': '阿策小和尚', 'age': 100, 'sex': 0};
People people = People.map(map);
print('People.name=${people.name}, age=${people.age}, sex=${people.sex}, hashCode=${people.hashCode}');
print('<---------------->');
People people2 = People.map(map);
print('People2.name=${people2.name}, age=${people2.age}, sex=${people2.sex}, hashCode=${people2.hashCode}');
print('<---------------->');
People people3 = People.fromMap(map);
print('People3.name=${people3.name}, age=${people3.age}, sex=${people3.sex}, hashCode=${people3.hashCode}');
print('<---------------->');
People people4 = People.fromJson(map);
print('People4.name=${people4.name}, age=${people4.age}, sex=${people4.sex}, hashCode=${people4.hashCode}');

      小菜先定义一个 _cache 缓存,在使用工厂构造函数 People.map() 时,先判断该实例是否已完成构造,若已存在则返回 _cache 实例,不存在则构建新的实例;如 Demo 中的 peoplepeople2,调用工厂函数时,people 是第一次构建,people2 在构建时 _cache 中已存在,因此无需重新构建;其中 peoplepeople2 对应的 HashCode 一致,说明两者是相同的对象;

注意事项

1. 构造函数具有传递性

      若在声明构造函数时,多个函数之间有类似的逻辑关联,为了减少代码冗余,可以通过函数传递来精简代码;小菜创建了一个 People.fromAdd() 构造函数,对于相同地方的 People 可以通过 People.fromBJ() 来传递到 People.fromAdd() 来实现;

People.fromAdd(this.name, this.address);
People.fromBJ(name) : this.fromAdd(name, '北京');

People people6 = People.fromAdd('阿策小和尚', '北京');
print('People6.name=${people6.name}, address=${people6.address}, hashCode=${people6.hashCode}');
People people7 = People.fromBJ('阿策小和尚');
print('People7.name=${people7.name}, address=${people7.address}, hashCode=${people7.hashCode}');

2. Factory 工厂构造函数可以实现单例

class Singleton {
  static final Singleton _singleton = Singleton.internal();

  factory Singleton() => _singleton;

  Singleton.internal();
}

      小菜对很多特殊情况的研究还不够全面,如有错误请多多指导!

来源: 阿策小和尚

1人推荐
随时随地看视频
慕课网APP