1. 程式人生 > >The Mapleton Pattern

The Mapleton Pattern

C++ Telltales part 6:

The Mapleton Pattern

This is sixth part of my C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series from my profile!

Singleton pattern is used to create a class that allows sharing the same instance of a class for multiple users. It’s useful when you want to store some shared data in a class (for example configuration values) that can be easily accessed and are non-changing between different callers. Singleton pattern is pretty simple to implement:

While singleton might be enough for most of the cases, you might also sometimes need multiple instances. This is where Mapleton pattern comes in. It can provide instances of the class with for example unique identifier string. Each of the instances will have their own member variables that are not shared between other instances. Simply put, the Mapleton can be implemented as follows:

It’s not always good to use these patterns though and one might think they are even evil. Sometimes they make sense so always consider if you really need a singleton or if you can handle the task at hand. And if you are using multi-threading, always remember to protect changes to member variables accordingly!

And here is the same image from my first part to get some cover photo for this article (still lazy):