簡體   English   中英

Dart 命名構造函數與 Static 方法更喜歡什么?

[英]Dart Named constructor vs Static method what to prefer?

所以在dart使new關鍵字可選之后,

我們可以使用完全相同的語法但不同的內部實現來初始化 object。

class Color {
  int r = 0, g = 0, b = 0;

  Color({this.r, this.b, this.g});

  //Named constructors
  Color.red() //Implementation

  Color.cyan() //Implementation

  // Static Initializers
  static Color red() => //Initialze with parameter

  static Color cyan() => //Initialze with parameter
}

無論named constructor還是static method ,我們都可以這樣使用它們:

Color red = Color.red();
Color cyan = Color.cyan();

使用它們每個的地方是什么?

構造函數和 static 函數不同。 您通常會創建一個命名構造函數,該構造函數返回具有一些預定義值的 object 實例。 例如,您有一個名為Person的 class 存儲NameJob 您可以創建這個命名構造Person.doctor(name) ,您將返回一個Person object ,其中Job = 'doctor'

 class Person{
  final name;
  final job;

  Person(this.name, this.job);

  Person.doctor(this.name, {this.job = "doctor"});

 }

Static 函數或變量持續存在於 class 的所有實例上。 假設, Person有一個名為count的 static 變量。 每當創建Person的實例時,就增加 count 變量。 您可以稍后在代碼中的任何位置調用Person.count以獲取count的值( Person的實例數)

class Person{
  final name;
  final job;
  static int count;

  Person(this.name, this.job){
    count++;
  }

  Person.doctor(this.name, {this.job = "doctor"});

}

實際上,工廠構造函數和 static 方法之間幾乎沒有區別。

對於通用 class,它會更改您可以(並且必須)編寫類型參數的位置:

class Box<T> {
  T value;
  Box._(this.value);
  factory Box.withValue(this.value) => Box<T>._(value);
  static Box<T> fromValue<T>(T value) => Box<T>._(value);
}
...
  var box1 = Box<int>.withValue(1);
  var box2 = Box.fromValue<int>(2);

因此,對於泛型類,工廠構造函數通常是您想要的。 他們有最令人愉快的語法。

對於非泛型類,差別很小,所以主要是關於信號意圖。 並決定名稱在 DartDoc 中屬於哪個類別。

如果 function 的主要目標是創建一個新的 object,則使其成為構造函數。

如果主要目標是進行一些計算並最終返回 object(即使它是一個新對象),請將其設為 static function。 這就是為什么parse方法通常是 static 函數。

簡而言之,做適合您的 API 的事情。

named constructorstatic function之間區別的另一個好處是,在生成的文檔中 function 將進一步歸檔在構造部分或方法部分中,以便讀者更清楚地了解。

在文檔的構造函數部分中尋找構造函數的人將很容易發現命名的構造函數,而不必也挖掘 static 函數部分。

static class 方法的另一個非常有用的特性是您可以使它們異步,即等待完全初始化,以防這取決於一些異步操作:

Future<double> getCurrentPrice(String ticker) async {
  double price;
  // for example, fetch current price from API
    price = 582.18;
  return price;
}

class Stock {
      String ticker;
      double currentPrice=0.0;
      
      Stock._(this.ticker);
      
      static Future<Stock> stockWithCurrentPrice(String ticker) async {
        Stock stock = Stock._(ticker);
        stock.currentPrice =  await getCurrentPrice (ticker);
        return stock;
      }
}

void main() async {
  Stock stock = await Stock.stockWithCurrentPrice('AAPL');
  print ('${stock.ticker}: ${stock.currentPrice}');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM