Singleton: Difference between revisions

Content added Content deleted
(Added non-thread-safe C++ version, subcategorized ObjC and C++ examples.)
Line 2: Line 2:


=={{header|C++}}==
=={{header|C++}}==

===Thread-safe===
'''Operating System:''' Microsoft Windows NT/XP/Vista
'''Operating System:''' Microsoft Windows NT/XP/Vista


Line 42: Line 44:
</pre>
</pre>


===Non-Thread-Safe===
This version doesn't require any operating-system or platform-specific features, but it is not safe in a multi-threaded environment.

<pre>
class Singleton
{
public:
static Singleton* Instance()
{
// Since it's a static variable, if the class has already been created,
// It won't be created again.
static Singleton myInstance;

// Return a pointer to our mutex instance.
return &myInstance;
}

// Any other public methods

protected:
Singleton()
{
// Constructor code goes here.
}
~Singleton()
{
// Destructor code goes here.
}

// And any other protected methods.
}
</pre>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
===Non-Thread-Safe===

(Using Cocoa's NSObject as a base class)
(Using Cocoa's NSObject as a base class)
<pre>
<pre>