Hi,
I can achieve the same functionality as of singleton by creating a static object.
So what is the advantage of using the singleton class or design pattern.
Plz correct me if I am wrong.
Thanks
Printable View
Hi,
I can achieve the same functionality as of singleton by creating a static object.
So what is the advantage of using the singleton class or design pattern.
Plz correct me if I am wrong.
Thanks
a static object is one possibility of implementing a Singleton. Another possibility would be to create a new object in the free store on the first access to the Singleton.
No, you can't. Singlteon means you have only one object of a such type with all the advantages of it whereas a static object is the static object only. It is not a replacement for the singleton. You should read more about the singleton http://sourcemaking.com/design_patterns/singletonQuote:
I can achieve the same functionality as of singleton by creating a static object.
Why,what extra advantage is there in Singleton
Rajesh1978, Did you read the text on the link i've posted above?
The point of the singleton pattern is supposedly to enforce only one instance of a particular class, but in practice it seems it's mostly used to wrap global state in a more attractive package. I'm generally not a fan of it.
It's essentially the same advantage over global state that full class objects have over data-only structures: It comes complete with methods to refine and manipulate that state, all wrapped up in a tidy package.
Could you achieve the same thing without a singleton, just using free functions? Absolutely. But that might not give you as useful of an abstraction about what's happening.
I think that I have seen what the OP is talking about. I have seen a pattern where all data members of the class are static. Even though you can create multiple instances, every instances reads and writes to the same class attributes, which are all static. In this case, the constructors are still public as are the member functions. Member functions are also non-static. Of course you still have to implement mutexes to protect the data in the case of multiple threads creating other instances. In some cases I have seen this done where all of the member functions are also static. In that case no instance is ever created.
The main problem I have with this is that it isn't a singleton by definition since there are multiple instances but the design realizes similar goals. It actually works and I have had a hard time criticizing it. The main problem is that static member functions can't be virtual so it is impossible to extend the pattern using inheritance. On the other hand, in most cases that I have seen inheritance wasn't really needed so the designer didn't care. I'm not sure if this is what the OP is talking about. In the past I've seen these and disliked them but didn't have a real good argument for insisting that they be designed into real singleton's at the time.
I've come to dislike singleton honestly. I think it is an overused pattern and for such a simple concept there seem to be a lot of complex issues associated with guaranteeing that only one instance can ever exist. There are plenty of other options for providing access to objects without using the singleton pattern and in a lot of cases there really isn't any danger of multiple objects being created unecessarily if factories and delegators are coded correctly.
To be honest, I am not sure what is meant by a static object. If the class declaration contains a public constructor then it isn't a singleton. The purpose of the singleton pattern is to "enforce" one and only instance of a type while providing a convenient way of accessing that one and only instance. If you have a type with a public constructor and you just create a static instance, there is nothing being enforced that would allow you to call that pattern a real implementation of singleton.
I don't disagree with that aspect of it. What get me is, you poll programmers about global state, and most will say it's a bad thing. Poll them again about singletons, and most tend to say that they're good. What's the difference?
There are certainly ways to get the encapsulation aspect and the single-instance aspect without having the global state aspect.
Heheh, I decided to check my copy of the GoF book, and yeah, that pattern is listed as one of the things that the singleton pattern can replace (and conversely, the singleton pattern is one of those things that that pattern can replace).Quote:
Originally Posted by kempofighter
Yes, though I'd say that you can still refer to that lone object as a singleton, literally speaking.Quote:
Originally Posted by kempofighter
I would say that "most tend to say that they're good" is an exaggeration, but my take is that the difference is because in those specific cases where one really needs to enforce the singleton property and a single point of access makes sense, the singleton pattern is tolerable (but woe to you if your requirements change too much!), whereas ordinary global variables give you global state with no mitigating factors (other than allowing you to be careless about design).Quote:
Originally Posted by Speedo
The primary problem with global data, as I see it, is that it's uncontrolled and makes thread-safety hard.
Singletons solve the second problem well enough. As for the first, that just requires careful design. Using a singleton helps to enforce the fact that you aren't just arbitrarily changing data; you're altering state which is designed and expected to be queryable in the first place.
a class with all static methods is not singleton it is a nothington that lacks polymorphism and a built-in mechanism for construction and destruction and hence you can make a hierarchy of classes when using nothington. in another point of view when using nothingnot there is no object orientation at all and in fact your class is a collection of some functions that is not good as perspective of design. this issue that constructor and destructor are called automatically when using singleton is a very important issue rather than using nothington.
Of course that's true in theory, but in practice it seems that singletons are a favorite point of abuse.
It also hides hides dependancies, which can make testing and reusing code a royal PITA.Quote:
The primary problem with global data, as I see it, is that it's uncontrolled and makes thread-safety hard.
The way I see it, singletons are simply OOP's answer to the occasional need for global state. Of course it's possible to abuse them.
One other option, if you don't want to code a singleton and polymorphism is not required, is to enclose the public functions in a namespace and declare the private functions and data in an anonymous namespace within the source file.
i.e.
.H.CPPCode:namespace My_Api
{
void Function2();
}
Code:// Private functions and data.
namespace
{
int a;
int b;
void Function1()
{
// Stuff
}
}
// Public functions and data.
void My_Api::Function2()
{
a = 0;
Function1();
}
I will prefer to deal with one static object and many non static field as like singelton than many objects who happend to work on many static field through their member functions.
I mean should not we be trying to cut down on usage of static when we are programming in object oriented language.
Regards
Prashant.
This is an old argument, but I thought I'd throw in my 2c. (I am Australian so I use 's' instead of 'z' in my spelling :) )
I consider the main points of a singleton class to be:
1. Guaranteed single instance only.
2. Ownership isn't obvious, so it looks after its own construction/destruction - lazy evaluation.
If these points are important to you, then use the good old create-on-first-use + static-member-variable + getInstance() function. There is nothing really wrong with it.
Some argue that this causes a pointer check (which can be inlined if the code is in the declaration file so not a real issue) and an indirection (pointer deference) for every call, which isn't as efficient as a direct call - especially when you know the thing is basically static. If you're going to go into a tight loop and call lots of functions off a class built like this, then do the getInstance() once into a pointer before the tight loop and then it just becomes a normal function call. No big deal, I'm sure you've got bigger fish to fry in your code than pointer dereferencing! Oh, and if you're going to allow multiple threads, please be careful and make sure the getInstance() function is protected!
On the other hand, I -personally- don't like lazy-evaluation of construction 99% of the time. I fall into the camp of explicit initialisation/construction. I could argue why, but that would be another thread :)
I come from game programming which tends to have a lot of Factory-type singletons: Core, Input, Renderer, Networking, I/O, Object creation Factory etc. These are all typical examples of singletons, in my work. They also typically require more sophisticated construction than the default constructor, so invariably have an init(blah, blah, blah) function. It's at this point I tend to diverge from the typical singleton pattern theory (because point 2 isn't important to me).
There are two options I can use:
1. Create a namespace and put all static functions (no data) in it, with everything else in the implementation file (.cpp). Have an explicit init()/uninit() pattern with ownership by the owning system, typically the application itself. This gets single instance, encapsulation, explicit construction (and destruction let's not forget!) and all calls are statically linked direct address calls.
2. Same as 1 but use a class instead of a namespace. If I do this, I make the constructor and destructor private, sending a message to readers of the class that it can't be derived or constructed on the stack/heap by any other class other than itself (single instance again). Note that like 1, all data is kept in the implementation file. Same benefits as 1 really, but some don't like the idea of a class having all static functions - they feel it's not very OOP, which I guess is true in that a purely static class is more a grouping of functions (i.e. namespace) than an instance of an object.
So, I tend to prefer the namespace approach. It's still called the same way as a static function in a class - MyClass::someFunc() - but doesn't confuse OO people who freak out seeing an all-static class :)
Keep in mind that the private data, held in the implementation file remember, is in a kind of uninitialised stated, and that the user of the namespace/class has direct function call access which means if they forget to call init() obviously there will be a problem. It's usually pretty obvious if this happens (instant crash on first function call :)). Also, I honestly think that good programmers should know the how and the order in which they are creating their system, so it doesn't hurt to see all the inits done in a nice big block at the start.
And always keep in mind that with an explicit initialiser you get to brace it with an explicit uninitialiser. This is very useful, and allows you to check all sorts of things before exiting an a application, in a specific order - not some random initialised order like a lazy-evaluation method.
One last point: threading. Again, you REALLY want to protect the getInstance() function against multiple threads potentially creating the singleton. Beware! This is another reason I like the explicit initialisation pattern. I use this pattern on consoles like the PS3 so I darn well know when a singleton is created and destroyed.
Anyhoo, could go on all day. That's my bit.
Shane
I always use the local static approach:
Code:class Something
{
public:
static Something& Instance();
private:
Something();
};
Something& Something::Instance()
{
static Something singleton; // will be constructed when
// the function is called
// for the first time.
return singleton;
}
As aready suggested here, implementing singletons is not quite a simple task as it seems to be.
I kindly recommend reading about singletons in Modern C++ Design By Andrei Alexandrescu.
Then think twice...
Additionally, I have attached here a simplified example about how a class intended to be singleton becomes a kind of "doubleton".
Well the cause is quite easy to be found and somebody may ask "Is it possible? Who did such a stupid thing?...". The answer is "Yes, in practice is possible... done by some wise super-architect, sleeping with GoF under his head". :D ;)
I agree with the exceptions-in-destructor point. I don't use exceptions in my line of work, so I need to have an explicit init(), which has the benefit of me knowing exactly when my singleton is created.
Another point I forgot to mention before, is the problem of memory allocation and lazy-evaluation when you're working inside a fixed memory system. Allocating a potentially large block of singleton/never-moving block of memory at some arbitrary point can effectively create a permanent split in memory. Consider this: you're application starts up and begins allocating it's objects, goes into a level (if you're a game), allocates some more stuff, which then all gets freed up nicely when you leave, then boom, you call some function to a singleton (maybe a function to a network manager to upload your highscores somewhere) for the first time, and it allocates a piece of memory on-first-use, which never moves. That just permanently reduced your maximum potential allocation block. Not nice if you're on a system like a PS3/Xbox360. This is why you create/init your permanent blocks of memory up front, right next to each other.
On a side note, look at the complexity of the Singleton class in Andrei Alexandrescu's book. It goes from being a fairly simple request of a single instance of something, lazily-evaluated, to a nightmare very quickly (order of creation/destruction/thread safety). It's over-engineering to the extreme for 99% of cases, IMHO.
I'll stick to my namespace-singleton method. Simple, hides data, single instance, known allocation pattern. If anything, it's just like coding in pure C (i.e. no class. I can see a joke here: "You're like C baby... no class") :)
My extra 2c
Shane
Just an aside note about exceptions-in-destructor: it's "nice" when dealing with whatever static analysis tool (in conjunction with a strong QA department :)) which complains that if you have any function call in the destructor, it's mandatory to catch potentially thrown exceptions.
As a result you can see "well written" destructors like
Code:CFoo::~CFoo()
{
try // Just to make the QA happy.
{
::DeleteCriticalSection(&m_cs);
}
catch(...)
{
// Not even Chuck Norris can catch an exception here. :-)
}
}
Even a try-catch block in a destructor is not enough - if the destructor is called due to an exception being thrown and it then somehow throws its own exception, we suddenly have two active exceptions at the same time (long before the catch block is encountered).
Also, DeleteCriticalSection is declared as extern "C" and the checking tool should therefore know that it never throws an exception, and C++ functions can have the no-throw declaration on their signature.
That is a good point. One workaround would be to manually access all the problematic singletons at application startup.
Well then I would hope that Chuck Norris doesn't write checking tools ... tools which really SHOULD know. :D