mirror of
https://github.com/iandinwoodie/cpp-design-patterns-for-humans.git
synced 2025-12-17 12:34:38 +03:00
Added singleton example source code.
This commit is contained in:
31
examples/creational/singleton.cpp
Normal file
31
examples/creational/singleton.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
#include <assert.h>
|
||||
|
||||
class President
|
||||
{
|
||||
public:
|
||||
static President& getInstance()
|
||||
{
|
||||
static President instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
private:
|
||||
President()
|
||||
{
|
||||
}
|
||||
|
||||
~President()
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
President& president1 = President::getInstance();
|
||||
President& president2 = President::getInstance();
|
||||
|
||||
// There can only be 1 president, so they must be the same.
|
||||
assert(&president1 == &president2);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user