Denis Sablukov
Denis Sablukov

Reputation: 3700

What advantages of factory constructor over standalone factory class or function?

I've just started learning Dart and I wonder what advantages of factory constructor over standalone factory class or function?

When we add new derived class then we need to change factory method inside of our abstract class, it is fine if we have its code, but if it comes with library - factory constructor becomes useless?

Or there is some mechanism to update factory method with info about derived classes? If it so, please share an example.

Upvotes: 0

Views: 147

Answers (1)

Kevin Moore
Kevin Moore

Reputation: 6181

factory lets you return subtypes, which is very useful.

For instance, you could have factory MyClass.empty => const _EmpytMyClass() and return a trivial implementation with no storage.

You can also use it to returned cached values if you want to have canonical instances of your class.

You can also use factory to call methods to create your instances. See here: https://github.com/dart-lang/json_serializable/blob/4033f6ad4e3c96bc2ed16d93c0995e11fcfe42df/example/lib/example.dart#L29

Upvotes: 1

Related Questions