Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a factory method in flutter/dart?

Tags:

flutter

dart

I'm following a book that uses a factory method to implement a class that is a singleton.

I understand that the main purpose of this is to have just one instance of the class; But what exactly the keyword "factory" does in flutter?

This is the piece of code that I'm referring:

static final DbHelper _dbHelper = DbHelper._internal();

DbHelper._internal();

factory DbHelper() => _dbHelper;

I supose that the _dbHelper is the single instance that is being create with the _internal named constructor and that the factory method returns this single instance, is that correct? Am I missing something?

like image 966
AT-martins Avatar asked Feb 09 '20 03:02

AT-martins


People also ask

What is the use of factory in flutter?

Factory Method is referred as a creational design pattern which provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. Also known as virtual constructors. Lets clear it with a small code.

Why do we use Factory Method?

Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.

Why do we use Factory Method design pattern?

The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.

What is the advantage of factory constructor?

The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.


1 Answers

You have it correct!

You can read more about factory constructors here: https://dart.dev/guides/language/language-tour#factory-constructors

like image 152
dshukertjr Avatar answered Sep 23 '22 00:09

dshukertjr