Created
November 23, 2022 22:24
-
-
Save marcel-ploch/d792fa5539c5191b2197368511f21e25 to your computer and use it in GitHub Desktop.
Singletons in Dart sind doch so einfach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MeinSingleton { | |
/// Unsere Singleton Instanz, die einmalig instanziiert wird | |
static final MeinSingleton _singleton = MeinSingleton._internal(); | |
/// Member Variable, die zugreifbar gemacht werden soll | |
late List<dynamic> data = []; | |
/// Factory Constructor, der die Instanz der Klasse zurückgibt, egal wann sie aufgerufen wird | |
factory MeinSingleton() { | |
return _singleton; | |
} | |
/// Privater Named Konstruktor | |
MeinSingleton._internal(); | |
void addEntry(dynamic value) { | |
data.add(value); | |
} | |
} | |
void main() { | |
/// instanziere meine Klasse | |
var s1 = MeinSingleton(); | |
s1.addEntry("Test"); | |
/// erstelle eine zweite instanz | |
var s2 = MeinSingleton(); | |
s2.addEntry("Test2"); | |
/// beide instanzen greifen auf die gleichen Daten zu | |
print(s1.data.length == s2.data.length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment