Archived

This topic is now archived and is closed to further replies.

Singleton versus Monostate Pattern

This topic is 5121 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

I''ve found myself using Monostates much more commonly recently, rather than the apparently more popular Singleton pattern. I''ve used Singletons in the past and found them to be overly elaborate for what they achieve. Off the bat, I''d like to say that I think single-instance classes are overused in modern game programming (at least at the amatuer level). I can imagine only a handful of subsystems that might truly need to utilize one such pattern, including: a global debugging system, resource management (spec. precaching), and message passing between subsystems. My question is this (and I''m assuming that you''re familiar with both patterns to a conversant degree; if not, please refrain from response): Are monostates not (1) more elegant, (2) less complex, (3) more efficient, and (4) less error-prone, in the same contexts as one might use a Singleton? I ask because, as I said, Singletons have been promoted wildly by the likes of Meyers, the GOF, and even Alandrescu (sp?), while virtually no emphasis has been placed on Monostates. I find them to be pretty functional in most circumstances, due to the fact that single-instance and single-state just seem to go hand-in-hand. Am I overlooking something? Discuss. Later, ZE. //email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

Share this post


Link to post
Share on other sites
One of the worst things about monostate systems is that the user doesn't know that there is really only 1 underlying object, which could cause some nasty bugs. I, too, think singeltons are used way too much. They promote global access, which is just as bad as having global variables. IMO I think singeltons are better because they are about as explicit as you can get, and you can overcome the global access thing by just refering to it in your main function and passing it as a parameter to other functions that need it.
EDIT: Oops, I don't think I answered all your questions:
1) monostates, IMO, are more elegant than singeltons
2) they are much less complex to make, but to the user there isn't much of a difference.
3) singeltons are more efficient memory-wise, but they are both as efficient speed-wise.
4) I think singeltons are less error-prone, acually (which I already mentioned above)

-------
"Hey, what about those baggy pants you kids are wearin' these days? Aren't they hip and cool and poppin' fresh?"-Peter Griffin
"Everytime I see an M followed by a dollar sign I just say "oh god" and go to the next post."-Neurokaotix
the D programming language

[edited by - brassfish89 on November 29, 2003 2:51:49 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
What is complex about making a singleton?


class singleton
{
public:
static singleton& instance()
{
static singleton eg;
return eg;
}
private:
singleton(){};
singleton(const singleton&){};
singleton& operator=(const singleton&){};
};


Typing time approx 30 seconds.. how is that complex?

Share this post


Link to post
Share on other sites
You misunderstand. Due to the fact that this is a comparison, there are grades of "complexity;" quite clearly, neither of these patterns is difficult to generate a sample case for. Having said that, would you not prefer this?

class monostate
{
public:
static bool service(...);

private:
static int data;
}

I mean, my gosh; you can even instantiate one of them and toss it all over the place without the need to monitor pointer validity or order of initialization (unless your monostate has some type of invariant, which it really oughtn''t). And every instantiation references the same data. It''s unified-state heaven!



Share this post


Link to post
Share on other sites
Guest Anonymous Poster
you cant get more unified than only being allowed one state

Share this post


Link to post
Share on other sites
quote:
(3) more efficient

I disagree, a Meyers singleton gets created only if it is actually needed. A monostate will have to be initialized everytime (thus creating it).

In situations where space is tight thats one reason to prefer it, but we''re talking about very tiny differences here.

Share this post


Link to post
Share on other sites
quote:
Original post by ZealousElixir
Off the bat, I''d like to say that I think single-instance classes are overused in modern game programming (at least at the amatuer level). I can imagine only a handful of subsystems that might truly need to utilize one such pattern, including: a global debugging system, resource management (spec. precaching), and message passing between subsystems.

I''d potentially argue that those might also not be good candidates for Singleton status, depending on the context.
quote:

My question is this (and I''m assuming that you''re familiar with both patterns to a conversant degree; if not, please refrain from response): Are monostates not (1) more elegant, (2) less complex, (3) more efficient, and (4) less error-prone, in the same contexts as one might use a Singleton?

In general, I''d agree. The fundamental difference between Singleton and Monostate is that Singleton focuses on singularity of identity, which is often the wrong focus when you just want to ensure singularity of state. You''re not the first person to have raised these issues. For example, read about the Python Borg pattern.
quote:

I ask because, as I said, Singletons have been promoted wildly by the likes of Meyers, the GOF, and even Alandrescu (sp?), while virtually no emphasis has been placed on Monostates.

There''s a lot of mileage to be had from Singletons due to the complexity of getting them right.

quote:
Original post by Anonymous Poster
What is complex about making a singleton?

Let me guess. You''ve never actually used Singletons in non-trivial contexts, right?

Share this post


Link to post
Share on other sites
quote:
Original post by ZealousElixir
Having said that, would you not prefer this?

class monostate
{
public:
static bool service(...);

private:
static int data;
}

That's not Monostate! OK, it kind of is, but the omission of non-static member functions misses the essence of Monostate.

[edited by - SabreMan on December 1, 2003 9:09:53 AM]

Share this post


Link to post
Share on other sites
Appears, that I again missed something :-) - I''m using singletons REALLY a lot and I never heard of monostates. Can you please explain me what are monostates about, and so on...

Oxyd



---
Unreadable code is code written on a piece of paper, but not the one, in which its programmer is using a space in place you don''''t.

Share this post


Link to post
Share on other sites
quote:
Original post by Oxyd
I''m using singletons REALLY a lot

I''d view that as a cause for concern. Singletons are generally bad.
quote:

Can you please explain me what are monostates about, and so on...

Have you Googled?

Share this post


Link to post
Share on other sites
Singletons are not BAD nor are Monostates GOOD

As far as I can tell many people like to yell and scream about the singleton vs ( monostate / shared proxy / borg ). In the end it appears that they acheive, for the most part, the exact same effect.

In all that I have read I think that I would still prefer to use singletons for the explicitness of the code. I also like the fact that any code can be converted to a singleton with just a few lines of code rather than a full refactoring.

Personally is you are using MANY singletons you might be better off using something more like the prototype or abstract factory pattern where all the code knows is that it requests an object of a type and an intermediate returns it ( can return a single instance if you want ). That way the code is simpler ( don''t have to actually make it a singleton, the intermediate will take care of that ) and you can swap out implemetations quickly and easly.

For further reading I recommend Design Patters by Gamma, et al.

Share this post


Link to post
Share on other sites
quote:
Original post by SabreMan
quote:
Original post by ZealousElixir
I can imagine only a handful of subsystems that might truly need to utilize one such pattern, including: a global debugging system, resource management (spec. precaching), and message passing between subsystems.

I''d potentially argue that those might also not be good candidates for Singleton status, depending on the context.

I would then be inclined to ask, in what context would said subsystems be candidates for being patterned after a single-state pattern? Secondarily, what is a practical example of a single-state class in game programming, if none of the above?

Later,
ZE.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by freakchild
quote:
Singletons are generally bad.


Care to offer some factual reasons for this Sabreman?
I doubt he meant the pattern itself is bad, for what it''s intended. But that globals and globals in disguises (singletons/monostates) should be avoided in general. For reasons, read this thread:
http://www.gamedev.net/community/forums/topic.asp?topic_id=169848

Share this post


Link to post
Share on other sites
The issue of globals and singletons is often confused. They are two entirely different things.

The purpose of the pattern is simply to ensure that only one instance of an object is created. This is a highly useful feature and does not mean that the object is ''global''.

Share this post


Link to post
Share on other sites
I think its the global access that is worrisome.

Imagine a group of programmers. One senior programmer assigns a younger programmer to write an algorithm to work in a worker thread. The jr. programmer copy-pastes some code that makes use of the singleton. Unless the singleton is protected by a critical section you have a possible race condition on your hands.

Now this could happen with anything, but without the ability to access it from anywhere you''d have to consciously get a reference to the item down into the worker thread, implying that you know what you''re doing and that maybe you''d think to protect the singleton.

Share this post


Link to post
Share on other sites
Singletons make life slightly easier when you find out that you need to go from Singleton, to single-instance, or even configured-instance modes. Monostate just breaks down there.

For example, suppose you have an EntityManager. Suppose you now want to structure your game networking code to have one server, and one client, that both run in the same address space. However, for game code cleanliness purposes, you want one EntityManager for the logically separate server part, and one EntityManager for the local player (if present). If you have a Singleton, you can take the code, rip out the instance() accessor and instead use a factory, and then configure your subsystems (local client and server system respectively) with their own instances. All accesses of EntityManager::instance() have to be changed to access the instance that''s configured on the subsystem.

Some systems draw this to extremes, and say that even if you use singletons, all your systems have to be configured with the singletons, so that such separation can happen.

Share this post


Link to post
Share on other sites
I have to agree with hplus0603 as to why to prefer singletons.
Best example I encountered is, say we have a Motor class, which should be a singleton as we can only have one motor, but then we encounter a system with a number of motors.(eg: left motor & right motor). Each motor class is practically identical, but still should be singleton-like. Easyer to transform a singleton than monostate.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by freakchild
The purpose of the pattern is simply to ensure that only one instance of an object is created. This is a highly useful feature and does not mean that the object is ''global''.
"Highly useful feature"? There''s only very few cases where ensuring one instance is a good, flexible choice, and even in those cases the global access adds transparent coupling so you''d be better off by forgetting about singletons.

Share this post


Link to post
Share on other sites
quote:
Original post by freakchild
Care to offer some factual reasons for this Sabreman?

Consider...

  • Lifetime management, particularly between interdependent singletons.

  • Conflation of class definition and creation policy concerns.

  • Potential implicit coupling of dependents.

  • Potentially solves a problem which arises in the solution domain, not the problem domain.


If you don''t like the way I''ve worded my comment, then consider the translation "usage of Singleton often signals a failure of abstraction". I''ve written about that topic on the forums before, but I''m having trouble finding my posts with the Search facility not fully working.

Share this post


Link to post
Share on other sites
quote:
Original post by freakchild
The purpose of the pattern is simply to ensure that only one instance of an object is created. This is a highly useful feature and does not mean that the object is ''global''.

The intent of the Singleton pattern is "Ensure a class only has one instance, and provide a global point of access to it". If it does not have a global point of access, it does not meet the intent, and therefore does not qualify as a Singleton.

Share this post


Link to post
Share on other sites
quote:
Original post by SabreMan
quote:
Original post by freakchild
The purpose of the pattern is simply to ensure that only one instance of an object is created. This is a highly useful feature and does not mean that the object is ''global''.

The intent of the Singleton pattern is "Ensure a class only has one instance, and provide a global point of access to it".


True, straight out of the book itself I see. However providing a global point of access to an object through a pattern such as a singleton, really doesn''t turn the object in question into something that is global, as in like the global variable/object that everyone seems to dislike. The object inside the singleton won''t even be in the global namespace.

Maybe it''s a small point that I make. I accept that people can, if they choose replace something like a global object with a singleton implementation. But this is a fault with the programmer and doesn''t at all mean that singletons are bad.

As for the other response as to why singletons are bad.

There is plenty of documentation around regarding managing the lifetime of a singleton. There should be no issue here.

Everything else you mention again comes down to the choices made by a programmer - not the fact that a singleton is bad, or indeed a bad choice itself.

Share this post


Link to post
Share on other sites
quote:
Original post by freakchild
However providing a global point of access to an object through a pattern such as a singleton, really doesn''t turn the object in question into something that is global

I think you''re missing the point. Global does not mean "is visible everywhere by default", it means "is accessible anywhere", which is sufficient condition for the problems of implicit coupling to arise. Its implicit coupling that''s the danger.
quote:

The object inside the singleton won''t even be in the global namespace.

It will be globally accessible.
quote:

There is plenty of documentation around regarding managing the lifetime of a singleton. There should be no issue here.

Much of that documentation describes the issues, but it does not make the issues go away. Neither does it tell you whether your specific use of a Singleton is a good use.
quote:

Everything else you mention again comes down to the choices made by a programmer - not the fact that a singleton is bad, or indeed a bad choice itself.

I already offered an alternate interpretation for the literal-minded... "usage of Singleton often signals a failure of abstraction".

Share this post


Link to post
Share on other sites