Dart
作为一门面向对象的编程语言,每个对象都是一个类的实例,所有的类都继承于 Object
类。
本节主要记录一下Dart
中关于类的构造函数
- 构造函数语法糖
- 命名构造函数
- 参数初始化列表
- 重定向构造函数
- 常量构造函数
- 工厂构造函数
构造函数语法糖
实际写法如下,省去java
中类似this.name = name;
的方法体
class Person {
String name;
int age;
String sex;
Person(this.name, this.age, this.sex);
}
void main() {
Person person = new Person("name", 20, "男");
}
命名构造函数
由于Dart
不支持类似Person(this.name);
Person(this.name, this.age);
的方法重载,而实际开发中经常存在一个类需要多个构造函数实例化,命名构造函数就应运而生了。实际使用就是在构造方法后添加. + 方法名
class Person {
String name;
int age;
String sex;
Person(this.name, this.age, this.sex);
Person.nameAndAge(this.name, this.age);
Person.nameAndSex(this.name, this.sex);
}
void main() {
Person person1 = new Person("name", 20, "男");
Person person2 = new Person.nameAndAge("name", 20);
Person person3 = new Person.nameAndSex("name", "男");
}
参数初始化列表
在构造函数函数体执行之前,会首先执行初始化列表,适合用来设置 final
变量的值。
Person.nameAndSex()
: name = "name",
sex = "男"{}
Person.fromMap(Map map)
: name = map['name'],
age = map['age'],
sex = map['sex']{}
重定向构造函数
实际开发中可能存在:一个构造函数调用类中的其他构造函数(在Java
中就是 this(...)
)。 一个重定向构造函数是没有代码的,在构造函数声明后,使用 :
调用其他构造函数。
class Person {
String name;
int age;
String sex;
Person(this.name, this.age, this.sex);
Person.nameAndAge(String name, int age) : this(name, age, null);
Person.name(String name) : this.nameAndAge(name, null);
}
常量构造函数
实际开发中,有些状态不变的对象需要重复使用(指向同块内存区域),可以把这种对象定义为编译时常量。用法:定义一个 const
构造函数, 并且声明类的所有变量为 final
。
class ConstantObject {
final int _x;
final int _y;
const ConstantObject(this._x, this._y);
ConstantObject.xy(this._x, this._y);
}
void main() {
ConstantObject o1 = const ConstantObject(0, 0);
ConstantObject o2 = new ConstantObject(1, 1);
ConstantObject o3 = new ConstantObject(0, 0);
ConstantObject o4 = const ConstantObject(0, 0);
ConstantObject o5 = new ConstantObject.xy(0, 0);
print(o1==o2);
print(o1==o3);
print(o1==o4);
print(o1==o5);
}
o1
与 o2
o3
o5
为不同对象,与 o4
同一对象,故
运行结果为false
false
true
false
工厂构造函数
- 使用
factory
关键词修饰的构造函数即为工厂构造函数。 - 工厂构造函数无法访问
this
- 这个构造函数不必创建类的新实例。例如,一个工厂构造函数可能从缓存中获取一个实例并返回,或者返回一个子类型的实例。
class Parent {
static Parent _instance;
factory Parent.getInstance() {
if (null == _instance) {
_instance = new Parent._newInstance();
}
return _instance;
}
Parent._newInstance();
}
class Parent1 {
static Parent1 _instance;
static Parent1 getInstance() {
if (null == _instance) {
_instance = new Parent1._newInstance();
}
return _instance;
}
Parent1._newInstance();
}
- 对比以上两个单例模式写法,实现效果是一致的,区别是
factory
修饰的是构造函数,需要返回一个实例,而static
是静态方法开发中可以灵活配置返回值。
网友评论