构造函数如何使用复杂算法初始化最终字段? [英] How constructors can initialize final fields with complex algorithm?

查看:92
本文介绍了构造函数如何使用复杂算法初始化最终字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个不可变的类Vector3。

  class Vector3 
{
final num x, y,z;
Vector3(this.x,this.y,this.z);
num get length => ...一些重的代码
}



现在,我想写一个构造函数,来自另一向量的单位向量。我想根据Dart的建议(避免在我们创建一个新的对象时写静态方法)。



我的问题是,我不能写这个构造函数因为最终字段必须在构造函数的body之前初始化,并且不能在里面初始化。我可以写如下:

  Vector3.unit(Vector3 vector)
:x = vector.x / vector。 length,
y = vector.y / vector.length,
z = vector.z / vector.length;

但是这很难过,我必须计算三倍的矢量长度...

我应该怎么做呢?我应该最终写一个静态方法来计算单位向量? (这将是一个耻辱)



最后,是不是可能在最终字段的初始化的构造函数体中写任何东西?



谢谢!

解决方案

使用工厂构造函数:

  class Vector3 
{
final num x,y,z;
Vector3(this.x,this.y,this.z);

factory Vector3.unit(Vector3 vector){
var length = vector.length;
return new Vector3(vector.x / length,vector.y / length,vector.z / length);
}

num get length => ...一些重代码
}


I am writing an immutable class Vector3.

class Vector3
{
  final num x, y, z;
  Vector3(this.x, this.y, this.z);
  num get length => ...some heavy code
}

Now, I want to write a constructor that computes the unit vector from another vector. I want to do that according to the Dart's recommendations (avoid writing a static method when we create a new object).

My problem is that I can't write this constructor because the final fields must be initialized before the constructor's body and cannot be initialized inside. I can write something like :

Vector3.unit(Vector3 vector)
  : x = vector.x / vector.length,
    y = vector.y / vector.length,
    z = vector.z / vector.length;

But this is so sad I have to compute three times the length of the vector...

How am I supposed to do that? Should I finally write a static method to compute the unit vector? (It would be a shame)

And, at last, isn't it possible to write anything in the constructor's body related to the initialization of the final fields? And why?

Thanks!

解决方案

Use a factory constructor:

class Vector3
{
  final num x, y, z;
  Vector3(this.x, this.y, this.z);

  factory Vector3.unit(Vector3 vector) {
    var length = vector.length;
    return new Vector3(vector.x/length, vector.y/length, vector.z/length);
  }

  num get length => ...some heavy code
}

这篇关于构造函数如何使用复杂算法初始化最终字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆