In the code below to implement the Singleton design pattern, we approach two different ways.
One of them creates Singleton but the other creates an object each time we call it.
What's the difference between ?? and =?? in the code below written in dart?
class ExampleStateByDefinition extends ExampleStateBase {
static ExampleStateByDefinition? _instance;
ExampleStateByDefinition._internal() {
initialText = 'A new "ExampleStateByDefinition" instance has been created.';
stateText = initialText;
print(stateText);
}
static ExampleStateByDefinition? getState() {
return _instance ?? ExampleStateByDefinition._internal(); //here we use ??
}
}
The above code creates an object each time we call it, so let us look at another variant:
class ExampleStateByDefinition extends ExampleStateBase {
static ExampleStateByDefinition? _instance;
ExampleStateByDefinition._internal() {
initialText = 'A new "ExampleStateByDefinition" instance has been created.';
stateText = initialText;
print(stateText);
}
static ExampleStateByDefinition? getState() {
_instance ??= ExampleStateByDefinition._internal(); //Here we use ??=
return _instance;
}
}
The above code implements Singleton by definition in Design Patterns: Elements of Reusable Object-Oriented Software