Using a factory constructor
Dart gives us many flexible and succinct ways to build objects through constructors:
With optional arguments, such as in the
Person
constructor wheresalary
is optional:class Person{ String name; num salary Person(this.name, {this.salary}); }
With named constructors (a bonus for readable self-documenting code), for example, where a
BankAccount
for the same owner asacc
is created:BankAccount.sameOwner(BankAccount acc): owner = acc.owner;
With
const
constructors, as shown in the following code:class ImmutableSquare { finalnum length; static finalImmutableSquare ONE = const ImmutableSquare(1); constImmutableSquare(this.length); }
However, modern modular software applications require more flexible ways to build and return objects, often extracted into a factory design pattern (for more information, refer to http://en.wikipedia.org/wiki/Factory_(object-oriented_programming)). Dart has this pattern built right into the language with factory constructors.