UNISA Chatter – Design Patterns in C++ Part 11: Patterns … Singleton versus Monostate
See UNISA – Summary of 2010 Posts for a list of related UNISA posts. This post is focused on my final preparations for the exam next week and chatter around the Singleton and Monostate patterns I have been having with fellow students.
… l oaned from book “Software Engineers on their way to Pluto”, showing the aftermath of an exciting year in terms of module COS3114
My final view … I hope it covers everything for the exam :)
The following mind map is my final summary for the exam preparations … the time has now come to dig through the assignments and previous exams and wrap my head around the information to be in a position to walk into the exam with confidence next Friday. One of the discussions (chatter) not shown on the mind map is the comparison of a singleton and a monostate pattern, which forms the remainder of this post.
Singleton versus Monostate … one (primarily mine) of the views
Let’s look at the code example for both patterns:
Singleton Pseudocode
1: public class SingletonPattern
2: {
3: private static SingletonPattern _instance = 0;
4: private SingletonPattern(){} // private constructor
5: public static SingletonPattern GetInstance()
6: {
7: // introduce locks when running in a multi-threaded environment
8: if ( _instance == 0 )
9: {
10: _instance = new SingletonPattern();
11: }
12: return _instance;
13: }
14: }
Monostate Pseudocode
1: public class MonostatePattern
2: {
3: private static int sharedValue = 0;
4: public MonostatePattern(){} // public constructor
5: //getter and setters
6: public void SetSharedValue (int newValue)
7: {
8: sharedValue = newValue;
9: }
10: public ing GetSharedValue()
11: {
12: return sharedValue;
13: }
14: }
Comparing Apples with Apples
Topic | Singleton |
Monostate |
Overview | Limits the instantiation to the class to one instance, which implies that it enforces the structure of a singularity. | Limits the data variables (state) contained within the class to one instance, without enforcing any structural constraints. |
Constructor | private … ensuring that the class cannot be instantiated, other than by itself. | public … allowing the instantiation of more than one instance of the class, both by itself and class consumers. |
Advantages |
|
|
Challenges |
|
|
So, when should I use which? If you need polymorphic derivations or logic, or a controlled lifetime of the objects, you should consider the Monostate Pattern. In all other cases, I recommend the Singleton.
… that’s it for this series. Fellow students, GOOD LUCK with the exam next week! May the exam be as interesting and slightly less challenging as the course this year :)