Posts Tagged ‘Design Patterns’

3 simple ways to create singleton pattern in C++

March 31st, 2011 5 comments

In my previous posts (part 1 and part 2), I’ve presented singleton design pattern implementation in C# .NET. In order to complete the subject, I would like to present singleton pattern implementation in old good native C++.

1) Basic singleton: static function “GetInstance” provides the access point; constructor, copy constructor and operator= are hidden from the user. The singleton is allocated upon first demand (lazy initialization). Null pointer is used to constrol first access, hence must be initialized in a C++ way – out of the class (as a static member).

class CKeyboard
	static CKeyboard* GetInstance() 
		if (!m_pInstance)
			m_pInstance = new CKeyboard();
		return m_pInstance;

	CKeyboard() {}
	CKeyboard(const CKeyboard&);
	CKeyboard& operator=(const CKeyboard&); 

	static CKeyboard *m_pInstance;

CKeyboard* CKeyboard::m_pInstance = NULL;

Read more…

Categories: C++, Design Tags: , ,

Simple singleton pattern with inheritance in C#.NET (part 2)

March 13th, 2011 1 comment

In my previous post about singleton inheritance, I’ve presented a simple singleton design pattern implementation in C#.NET, and a more advance implementation method, which allows to inherit from base singleton class. In the curent post, I will show several ways, to make the singleton thread-safe.
While saying “thread-safe singleton”, one usually means the singleton creation; another functions/properties are handled regular way to be threadsafe. Singleton creation must take place only once.
Classic pattern, providing a solution for this issue, is double-checked locking. Why 2 checks are needed? Because, after the first time creation, the lock is redundant. So we just prevent it by additional check. Using this pattern, singleton creation looks like this:

Read more…

Categories: .Net, Design Tags: , , ,

Simple singleton pattern with inheritance in C#.NET (part 1)

March 12th, 2011 No comments

Singleton is very simple and widely used Design Pattern. This pattern is described in a lot of blogs, articles and books (e.g. GoF = Gang of Four). According to GoF,  singleton’s job is to “Ensure a class has one instance, and provide a global point of access to it”. In a general case, singleton can be extended, in order to ensure a class has n instances, while 1 ≤ n < ∞.

How can one build a singleton?

Two steps to make some class to be a singleton:
1) Forbid straightforword creation => let constructor be private (or protected in some cases).
2) Provide general access point => static property (or function), which allows an access to object.

Let’s see the code:

Read more…

Categories: .Net, Design Tags: , , ,