Sign in to follow this  

Understanding Singleton Pattern

This topic is 3502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Could someone explain to me, how to use a singleton pattern? I tried following this tutorial but I tried to make it on my own and I am getting errors. main.cpp: undefined refrence to Singleton<Data>::Instance(); main.cpp: undefined refrence to Singleton<Data>::ptr_getSingleton()->PrintData(5); What would I even Define for these to work?
//Singleton.h
template<class T>
class Singleton
{
	private:
		static T *m_instance;
	protected:
		Singleton();
	public:
		static T *Instance();
		static T &ref_getSingleton();
		static T *ptr_getSingleton();
};

//Data.h
class Data
{
	private:
	int iData;
	public:
	int PrintData(int iData)
	{
		std::cout << iData << std::endl;
	}
};

#include <iostream>
#include "Singleton.h"
#include "Data.h"

int main()
{
    Singleton<Data>::Instance();
	Singleton<Data>::ptr_getSingleton()->PrintData(5);
    return 0;

}

Share this post


Link to post
Share on other sites
Okay, not to be rude but since it seems that you're pretty new to programming I'd recommend the best course of action is to forget you ever learned about the Singleton pattern. It normally leads to horrid code and in 99.9% of cases is actually the wrong choice. If you do a search for singleton on these forums a lot of very smart people have already explained why its a bad idea.

In most cases if you need global access to something, make it a global, like a logger. The only time I can see justifying a Singleton is when you have a hardware limitation that only allows one instance. Otherwise if you only want one Resource Pool (what most would call a manager) then just create one. Enforcing limitations on programmers by using a Singleton is the wrong way to do things.

Share this post


Link to post
Share on other sites
The compilation fails because the compiler cannot find the implementation of Singleton<Data>::Instance() (the member function Instance() of a Singleton template compiled with Data as the template parameter). You can get it to compile by defining the member function in the header file.


//Singleton.h
template<class T>
class Singleton
{
private:
static T *m_instance;
protected:
Singleton()
{
// implement this here
}
public:
static T *Instance()
{
// implement this here
}
static T &ref_getSingleton()
{
// implement this here
}
static T *ptr_getSingleton()
{
// implement this here
}
};



Share this post


Link to post
Share on other sites
I'd suggest that you search the forum archives using the keyword 'singleton' and read three or four threads on the topic.

Meanwhile, out of curiosity, how are you planning to use your singleton class? What problem is it exactly that you're trying to solve?

Share this post


Link to post
Share on other sites
I was going to rebuild a 2d engine to find out how it works and it uses the singleton pattern in it. So I decided to look it up also.
http://gpwiki.org/index.php/SDL:Tutorials:Complete_2D_Engine_Overview
http://wiki.gamedev.net/index.php/Singleton_pattern



[Edited by - monp on May 13, 2008 9:46:30 PM]

Share this post


Link to post
Share on other sites
I am using the same data.h and used a different singleton.h and I am down to one error now. GetSingletonPtr not a member of Singleton<Data>


//singleton.h
#ifndef SINGLETON
#define SINGLETON

template<class T>
class Singleton
{
private:
Singleton();
~Singleton();
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
public:
static T* GetSingletonPtr();
{
static T m_Instance;
return &m_Instance;
}
};

#endif




#include <iostream>
#include "Singleton.h"
#include "Data.h"

int main()
{
Singleton<Data>::GetSinlgetonPtr()->PrintData(5);
return 0;

}

Share this post


Link to post
Share on other sites
Finally fixed it, Thanks for correcting the typo. After that i needed to define the constructor and destructor and it worked.

Share this post


Link to post
Share on other sites
Quote:
Original post by Mike2343
Okay, not to be rude but since it seems that you're pretty new to programming I'd recommend the best course of action is to forget you ever learned about the Singleton pattern. It normally leads to horrid code and in 99.9% of cases is actually the wrong choice. If you do a search for singleton on these forums a lot of very smart people have already explained why its a bad idea.

In most cases if you need global access to something, make it a global, like a logger. The only time I can see justifying a Singleton is when you have a hardware limitation that only allows one instance. Otherwise if you only want one Resource Pool (what most would call a manager) then just create one. Enforcing limitations on programmers by using a Singleton is the wrong way to do things.


Not to be rude, but not everyone learns programming on the same course. Singletons are one of the design patterns because they are a design pattern, and they are still taught quite heavily in courses on design patterns. I'm not ninja by any means, but it was rather late into my course studies that I learned design patterns. Since then, I've found them useful once in awhile.

Share this post


Link to post
Share on other sites
The problem with the singleton is that it solves an extremely niche case, is far too easy to implement, is entirely too popular given its limited applicability, gives beginners a false sense of sophistication, and is the least useful of the available design patterns. I wish beginners were learning MVC or adapter or observer like this.

Personally, I don't even consider the singleton to be a design pattern - there's a huge difference between "I only need one" and "There can be only one," and the fact that it conflates the two makes it suspect to me.

Share this post


Link to post
Share on other sites
is it me or has there been a ridiculous amount of threads about singleton threads lately?

I agree with Oluyesi, I think beginners like to use Singletons because it makes their code more fancy or something, but it probably has more to do with overdesign thing. As coders, i think we have an innate urge to organize our programs, and make the "perfect" and "organized" framework, but we sometimes forget the program is going to start somewhere, and you'll have your chance to create whatever object you wanted to be a singleton there.

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
The problem with the singleton is that it solves an extremely niche case, is far too easy to implement, is entirely too popular given its limited applicability, gives beginners a false sense of sophistication, and is the least useful of the available design patterns. I wish beginners were learning MVC or adapter or observer like this.

Personally, I don't even consider the singleton to be a design pattern - there's a huge difference between "I only need one" and "There can be only one," and the fact that it conflates the two makes it suspect to me.


This may be true, but I believe that the singleton lies at the top of the design pattern teaching methods. It is only a vehicle to teaching exactly what design patterns are, which runs counter to your claim that it is not, in fact, a design pattern.

I have to assert that Singletons are a design pattern, because they reemerge time and again, thus sufficing its definition as a design pattern. I don't deny that the singleton is overused or misused, however it remains an extremely useful tool in explaining design patters and in designing other pattens.

In essence, if you are to explain design patterns at all, you must first explain the Singleton.

Share this post


Link to post
Share on other sites
Quote:
Original post by ibebrett
is it me or has there been a ridiculous amount of threads about singleton threads lately?

I agree with Oluyesi, I think beginners like to use Singletons because it makes their code more fancy or something, but it probably has more to do with overdesign thing. As coders, i think we have an innate urge to organize our programs, and make the "perfect" and "organized" framework, but we sometimes forget the program is going to start somewhere, and you'll have your chance to create whatever object you wanted to be a singleton there.


Agreed, but is the pattern bad or the teaching bad? I use singletons once in awhile, does that make me evil or the reason I use them evil?

Share this post


Link to post
Share on other sites
Quote:
Original post by ibebrett
is it me or has there been a ridiculous amount of threads about singleton threads lately?

I think there's always a ridiculous amount of threads about singletons...
I think someone made a list in their journal once - it was a pretty long list.

Share this post


Link to post
Share on other sites
Quote:
Original post by argonaut
I have to assert that Singletons are a design pattern, because they reemerge time and again, thus sufficing its definition as a design pattern.

The need for a singleton does not emerge time and time again. The desire to use one does, which is not the same thing, and which does not qualify the singleton as a design pattern. In the last five years, I think I have only heard one case where a singleton was legitimately required.

Quote:
In essence, if you are to explain design patterns at all, you must first explain the Singleton.

Utter rubbish.

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
Quote:
Original post by argonaut
I have to assert that Singletons are a design pattern, because they reemerge time and again, thus sufficing its definition as a design pattern.

The need for a singleton does not emerge time and time again. The desire to use one does, which is not the same thing, and which does not qualify the singleton as a design pattern. In the last five years, I think I have only heard one case where a singleton was legitimately required.

Quote:
In essence, if you are to explain design patterns at all, you must first explain the Singleton.

Utter rubbish.


I am not denying that Singletons get overused or misused, but they are definitely an emergent pattern. However, I am in software development and we find that sometimes (about once a year, or so) that Singletons do come into use.

My main point was that this is part of the learning process, so don't call the guy a "noob" for asking about singletons. If someone is new, let them learn when a Singleton comes in. It's part of the learning process ... advice is fine, but calling them a "noob" [sic] is not.

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
Quote:
Original post by argonaut
I have to assert that Singletons are a design pattern, because they reemerge time and again, thus sufficing its definition as a design pattern.

The need for a singleton does not emerge time and time again. The desire to use one does, which is not the same thing, and which does not qualify the singleton as a design pattern. In the last five years, I think I have only heard one case where a singleton was legitimately required.


To address this idea of Singletons as an emergent idea, this is exactly what the "static" keyword introduces in C++. "static" as a keyword was introduced somewhere about 1986?

Share this post


Link to post
Share on other sites
Though I agree with argonaut, I think both the popularity and loathing of the singleton pattern can be explained by poor education and/or understanding about propper object interactions. The singleton pattern simply allows people to quickly call some code or refer to an object globally in an OO environment, without thinking about how it should actually fit into the OO model.

For example, it looks much easier at first to call GameSingleton.GetInstance().DrawSomeStuff() than to actually figure out how the drawing logic could be elegantly expressed in a more practical model. The popularity of this approach might seem warranted, since naively put

1) We're working with objects, so it's propper OOM
2) We're using the singleton 'pattern', so it's elegant OOM

Upon closer inspection it's obvious that the singleton applied in this (typical) way just abuses the OO facilities of a language to call some code globally and it has little to do with OOM at all. In my experience though, these subtleties are typically neglected in education (both formal and informal) and the focus lies on droning patterns into students and demonstrating them pretty much exclusively in textbook examples.


Yes, I'm sure this discussion has been beaten to death, but I thought it might be more useful than to simply re-re-post the "singletons are bad" dogma.

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
The need for a singleton does not emerge time and time again. The desire to use one does, which is not the same thing, and which does not qualify the singleton as a design pattern. In the last five years, I think I have only heard one case where a singleton was legitimately required.

I've had to use them quite often recently when having to write "integration layers" on top of legacy 3rd party libraries. My requirements tell me to turn the library into "some kind of modern class library", but the legacy code tells me that it will crash if I instantiate more that one of certain objects that it provides.

I am legitimately justified in applying the Singleton or Monostate pattern here? Or am I just imagining the constant emergence of this need in my work?

Yes it often gets used unnecessarily used, but it also has legitimate uses, which (depending on the area that you're working in) can come up more often that you would have us believe.

Share this post


Link to post
Share on other sites
And for good measure:

Quote:
Original post by Hodgman

...

Yes it often gets used unnecessarily used, but it also has legitimate uses, which (depending on the area that you're working in) can come up more often that you would have us believe.


I wholeheartedly agree. Elegant OOM design is one thing, but it doesn't always go well with getting stuff to work in a reasonable amount of time and without introducing mindboggling complexities. It's such a thin line between complex OOM and YAGNI. Pragmatism FTW! [smile]

Share this post


Link to post
Share on other sites
Quote:
Original post by remigius
And for good measure:

Quote:
Original post by Hodgman

...

Yes it often gets used unnecessarily used, but it also has legitimate uses, which (depending on the area that you're working in) can come up more often that you would have us believe.


I wholeheartedly agree. Elegant OOM design is one thing, but it doesn't always go well with getting stuff to work in a reasonable amount of time and without introducing mindboggling complexities. It's such a thin line between complex OOM and YAGNI. Pragmatism FTW! [smile]


Nice! I could not have (and, in fact did not) put the entire argument into a tighter scope. I salute you, sir!

Share this post


Link to post
Share on other sites
Quote:
Original post by Hodgman
I am legitimately justified in applying the Singleton or Monostate pattern here? Or am I just imagining the constant emergence of this need in my work?
The checklist in this article on Singletons suggests that a singleton would be justified if the following conditions are true:
  1. Is there a need for the considered functionality to be grouped in an object?
  2. Is there a need for the considered functionality to be grouped in a class?
  3. Is there a technical reason for which the considered functionality does not allow multiple instances of the class?
  4. Is there a need for the unique instance to be globally accessible?

Have a read of the article for a more in-depth look at each of those items and the reasoning behind it. Your description doesn't go into a great deal of detail, but the requirement for global access may not be neccesary in your example.

Quote:
Original post by argonaut
In essence, if you are to explain design patterns at all, you must first explain the Singleton.
There's absolutely no reason you couldn't teach the idea of design patterns without mentioning Singletons at all, nor are singletons neccesarily a best first place to start if you're teaching specific design patterns rather than just introducing the concept. They may well be a valid option as a first pattern to teach or relatively simple example of the idea of a design pattern (I'd personally avoid them, as I consider them to be very overused and often poorly understood, and therefore may be better left till the programmer is a bit more experienced), but "may first explain the Singleton" is very different from "must first explain the Singleton" as you suggested.

Quote:
Agreed, but is the pattern bad or the teaching bad? I use singletons once in awhile, does that make me evil or the reason I use them evil?
The abuse of the Singleton pattern is of course due to misunderstanding and misapplication, which may be a result of poor education on the subject. The pattern itself is certainly valid in some (I would suggest rare) cases, and generally when a capable programmer refers to a construct as "evil" they do understand that and are rather indicating that due to common overuse and/or misunderstanding people (particularly those who may be knew to the construct or pattern in question) should take additional care that their usage is indeed appropriate.

We know the pattern is appropriate and useful sometimes, but are suggesting that those cases are rarer than a lot of people think and that more thought should be put into possible alternatives before jumping in with the pattern. Learning about Singletons is not a requirement for understanding the underlying concept of design patterns, nor is knowledge of it prerequisit for learning most other design patterns, so it need not neccesarily be the first pattern someone is taught.

[Edited by - jbadams on May 14, 2008 3:40:06 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by jbadams
... when a capable programmer refers to a construct as "evil" they do understand that and are rather indicating that due to common overuse and/or misunderstanding people (particularly those who may be knew to the construct or pattern in question) should take additional care that their usage is indeed appropriate.

We know the pattern is appropriate and useful sometimes, but are suggesting that those cases are rarer than a lot of people think and that more thought should be put into possible alternatives before jumping in with the pattern. Learning about Singletons is not a requirement for understanding the underlying concept of design patterns, nor is knowledge of it prerequisit for learning most other design patterns, so it need not neccesarily be the first pattern someone is taught.


I don't think anyone has taken an issue with branding it as "evil", but rather with only doing the branding and very little explaining. Of course you'll get a discussion when such blanket statements are made (and n00bness is derived) without further clarification or justification.

Whether or not singletons are the mandatory first pattern is up for debate, but I think the discussion in this thread alone and misunderstanding in general makes it clear that singletons should be taught in depth. Specifically, it would make a perfect case to show how easy it is to misunderstand and/or abuse patterns and that patterns are by no means the holy grail of OOM by themselves.

Share this post


Link to post
Share on other sites

This topic is 3502 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this