Skip to content

Instantly share code, notes, and snippets.

@wtoalabi
Last active March 13, 2019 14:09
Show Gist options
  • Save wtoalabi/42f96b0401ef69b2a919c3820dc39549 to your computer and use it in GitHub Desktop.
Save wtoalabi/42f96b0401ef69b2a919c3820dc39549 to your computer and use it in GitHub Desktop.
Factory Constructor in my understanding
//The user factory constructor, when called will return the same instance, no matter how many times. Hence, the name singleton.
main(){
var user1 = User();
user1.name = "Mike";
user1.age = 3;
var user2 = User();
print([user1, user2]);
}
class User{
String name;
int age;
static final User _singleton = User._internal();
// There is a _singleton property that contructs the user class using the internal named constructor.
//This action is done once. As you see, the _singleton is a final property.
// Its value does not change.
//Anytime it is called upon, it just returns the constructed user object that was constructed using the named construtor(_internal).
factory User(){
return _singleton;
}
// So, whenever the factory User() constructor is called upon, it returns the _singleton object.
//Of course, this returns the User object that was initially created at the beginning.
User._internal();
// This is a valid constructor.
// It is as good as calling User().
@override
String toString() {
return 'User{name: $name, age: $age}';
}
}
// Therefore, anytime we call User() constructor, we are actually calling the factory constructor, which returns the _singleton object.
// Which has a value of a constructed User object.
//Call User() as many times as you like, you get the same object returned to you!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment