Understanding Factory constructor code example - Dart

后端 未结 4 1585
谎友^
谎友^ 2020-12-04 09:24

I have some niggling questions about factory constructors example mentioned here (https://www.dartlang.org/guides/language/language-tour#factory-constructors). I am aware o

4条回答
  •  执笔经年
    2020-12-04 09:50

    1) There is not much difference between a static method and a factory constructor.

    For a factory constructor the return type is fixed to the type of the class while for a static method you can provide your own return type.

    A factory constructor can be invoked with new, but that became mostly irrelevant with optional new in Dart 2.

    There are other features like redirects rather rarely used that are supported for (factory) constructors but not for static methods.

    It is probably still good practice to use a factory constructor to create instances of classes instead of static methods to make the purpose of object creation more obvious.

    This is the reason a factory constructor is used in the example you posted and perhaps because the code was originally written in Dart 1 where it allowed to create a logger instance with new like with any other class.

    2) Yes this is a named constructor and the prefix _ makes it a private named constructor. Only named constructors can be made private because otherwise there would be no place to add the _ prefix.

    It is used to prevent instance creation from anywhere else than from the public factory constructor. This way it is ensured there can't be more than one Logger instance in your application. The factory constructor only creates an instance the first time, and for subsequent calls always returns the previously created instance.

提交回复
热议问题