what pattern forces a class to have a single instance?
Flutter Pattern Patterns: i — Singleton
An overview of Singleton design design and its implementation in Sprint and Palpitate
First of all, I would like to thank you all for the support after publishing the introduction article to this series. Honestly, I have non expected that amount of people to not only be interested in the creation of mobile applications using Flutter but who are too willing to learn more most the Dart language itself, OOP design patterns and their appliance, lawmaking compages or software engineering science in full general. This encouraged me to dive straight into the research, coding, and hence, I present you the first design design in the serial — Singleton.
What is Singleton?
Singleton is a creational pattern pattern that ensures that a class has simply one case and also provides a global bespeak of access to it. The motivation for this pattern is stated in the GoF book:
It'southward of import for some classes to have exactly one case. Although in that location tin be many printers in a organization, there should exist just one printer spooler. In that location should be only i file organisation and i window managing director…
The master thought of this design is to brand a class itself responsible for keeping track of its sole instance. Singleton is considered one of the simplest design patterns but it is also an easy one to get wrong if you are not careful. So let's move to the analysis and analyze the details of Singleton and its implementation.
Analysis
To begin with, I must mention that in the series you will find several UML form diagrams in each commodity. If you are not familiar with grade diagrams and their note, I strongly recommend you to read this reference.
Class diagram and bones structure
A general approach to the implementation of Singleton is represented in the class diagram beneath:
- Singleton class contains the static property instance which is a reference to the course instance itself (this human relationship is represented as an association link from the grade Singleton to itself);
- This instance is only accessible through the static method getInstance();
- Grade constructor is marked as private (information technology could be protected in other implementations) to ensure that the form could not be instantiated from outside the grade.
Applicability
Singleton could be used in cases where creating the instance of a class is expensive eastward.grand. instantiating a form requires loading a lot of data from external sources. Besides, the pattern helps when you need to access the same object over and over once again beyond your code due east.grand. logger (this problem is usually resolved by applying another design pattern — dependency injection, only that's a topic for the future 😊). Singleton could too be used when some kind of caching layer is needed — the singleton class could check and manage the cache on the instance request.
General thoughts and dangers
- When designing a Singleton, lazy construction should exist considered — class instance should only be created when it is first needed;
- In general, the Singleton course should non require parameters for its construction. If your grade pattern requires a parameter, it could pb to the creation of a somehow different object based on that parameter — could this course all the same be called a Singleton, so? Some resources country that this is a valid approach, only I take a unlike opinion;
- Thread rubber — you should be enlightened of Singletons in multi-threaded applications. If they hold some kind of mutable information, it could pb to unexpected results, and so the synchronization machinery should be considered.
Since nosotros are talking about the Dart programming language in this series, you lot should know that Dart is a single-threaded programming language and its code runs in a little isolated space on the machine, chosen isolate. Hence, you should not worry about the thread-condom when implementing Singletons in Sprint as long as you practise non create a new divide isolate from the code past yourself. If y'all are not familiar with this topic, I strongly recommend you watch this video about isolates and event loops in Dart and Flutter. - In some cases, the Singleton design design is considered an anti-pattern. That is because it violates one (actually, more than one, but this example, in my opinion, is the all-time i) of the SOLID principles — the single responsibleness principle. In addition to the main responsibility of the Singleton class, it should as well manage its example lifetime which is a divide concern. Also, the utilise of Singletons makes it hard to unit test the code since information technology is non possible to mock a Singleton unless you provide some kind of interface that serves every bit its type.
Implementation
We volition employ the Singleton design pattern to save our Singleton example's state in the Palpitate Design Patterns application. To make it more straightforward, the state saves only a single text belongings. Example's state itself is implemented in three different means:
- Using a Singleton pattern blueprint which is implemented past definition;
- Using a Singleton design pattern which is implemented using the Dart language capabilities;
- Without using a Singleton at all.
ExampleStateBase
Since the example's state is implemented in several unlike ways, its abstraction was created in guild to reuse information technology in all of the implementations. Hence, course ExampleStateBase provides this abstracted country:
As already mentioned, the case'due south state consists merely of a single String property stateText and its initial value initialText. Properties stateText ant initialText are marked every bit protected — it is needed to make these properties attainable only for those classes which extend the ExampleStateBase class. However, Dart does non support the protected visibility in the aforementioned way every bit some of y'all could expect information technology to exist coming from the other OOP language'south groundwork such every bit C# or Java — we can just annotate these backdrop every bit protected simply it is more than as a reminder for the developer not to use them from outside of the class scope (Visual Studio Code editor even shows a warning in this example). Also, ExampleStateBase provides methods to operate the stateText.
Singleton'south implementation past definition
In the class diagram beneath, concrete classes of the Palpitate Pattern Patterns application are represented which implement the Singleton design pattern by definition.
- ExampleStateByDefinition extends the ExampleStateBase class to obtain admission to the land (in this case, stateText and initialText) and its methods.
- ExampleStateByDefinition implements the Singleton design pattern and handles the instance cosmos. The instance is only accessible through the static method getState().
Code of the ExampleStateByDefinition:
Singleton's implementation using Dart magic
Grade ExampleState implements a Singleton blueprint blueprint "the Dart style":
Past comparing this code with the previous implementation, you lot could detect that the static method getState() is missing — well, it is just not needed anymore! Dart language provides a factory constructor. It is used to implement a constructor that does non always create a new instance of its class — it is a nice and elegant way to implement the class every bit a Singleton, isn't it? Now you can create the instance of ExampleState grade by calling its manufacturing plant constructor in the same style as you lot would do that by calling a default ane — factory constructor volition create a new instance or render the existing one if it was already initiated.
ExampleStateWithoutSingleton
Just a elementary implementation of the state form without bothering it with Singleton or any other "fancy-schmancy" design patterns.
Example
First of all, a markdown file is prepared and provided as a pattern's description:
The instance itself uses all three different implementations of the state:
Singleton implementations (ExampleStateByDefinition and ExampleState) create a new state object only on the first creation of the SingletonExample widget, merely the ExampleStateWithoutSingleton instance is created on each creation of the SingletonExample widget. This behaviour could be noticed by changing the country and forcing the example's widget to rebuild e.k. by switching tabs:
Or by navigating to the main menu and back:
As you lot tin come across, the state which is implemented as a Singleton remains the same since a new case of the state course is not created on the example's widget rebuild.
All of the code changes for the Singleton pattern pattern and its example implementation could be found hither.
Your contribution
👏 Press the clap push beneath to prove your support and motivate me to write amend!
💬 Leave a response to this commodity by providing your insights, comments or wishes for the serial.
📢 Share this article with your friends, colleagues on social media.
➕ Follow me on Medium.
⭐ Star the Github repository.
Source: https://medium.com/flutter-community/flutter-design-patterns-1-singleton-437f04e923ce
0 Response to "what pattern forces a class to have a single instance?"
Post a Comment