... | @@ -4,7 +4,7 @@ A singleton is a class that can be **instantiated only once**: this can be very |
... | @@ -4,7 +4,7 @@ A singleton is a class that can be **instantiated only once**: this can be very |
|
|
|
|
|
In boardcore, you can achieve this by extending the Singleton template which you can find in `src/shared/`.
|
|
In boardcore, you can achieve this by extending the Singleton template which you can find in `src/shared/`.
|
|
|
|
|
|
## Methods
|
|
## Implementation
|
|
The Singleton interface is a template class which exposes a single method:
|
|
The Singleton interface is a template class which exposes a single method:
|
|
```cpp
|
|
```cpp
|
|
inline static T* getInstance()
|
|
inline static T* getInstance()
|
... | @@ -17,6 +17,9 @@ What this method does is: |
... | @@ -17,6 +17,9 @@ What this method does is: |
|
- If an instance of this class already exists, return that instance.
|
|
- If an instance of this class already exists, return that instance.
|
|
- If an instance of this class does not exist yet, create and return a new one.
|
|
- If an instance of this class does not exist yet, create and return a new one.
|
|
|
|
|
|
|
|
> :warning: **WARNING: By definition, a Singleton is an object whose constructor is defined _private_ !**
|
|
|
|
> **In order to instantiate it or get a reference, the _getInstance()_ method has to be called.**
|
|
|
|
|
|
## Example
|
|
## Example
|
|
|
|
|
|
From the `Singleton.h` comment:
|
|
From the `Singleton.h` comment:
|
... | @@ -27,7 +30,26 @@ From the `Singleton.h` comment: |
... | @@ -27,7 +30,26 @@ From the `Singleton.h` comment: |
|
*/
|
|
*/
|
|
class Foo : public Singleton<Foo>
|
|
class Foo : public Singleton<Foo>
|
|
{
|
|
{
|
|
|
|
friend class Singleton<Foo>;
|
|
|
|
|
|
|
|
public:
|
|
|
|
void someFunction()
|
|
|
|
{
|
|
|
|
... // do stuff
|
|
|
|
}
|
|
private:
|
|
private:
|
|
Foo() {} // private constructor
|
|
Foo() {} // PRIVATE CONSTRUCTOR
|
|
};
|
|
};
|
|
```
|
|
```
|
|
|
|
|
|
|
|
And in the main:
|
|
|
|
```cpp
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
Foo* foo = Foo::getInstance();
|
|
|
|
|
|
|
|
foo->someFunction();
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
``` |
|
|
|
\ No newline at end of file |