How to avoid singleton

Started by
9 comments, last by Khatharr 11 years, 5 months ago
I started a new project and I feel like I'm using singleton for everything.

For instance, I have skills that a character can do. I implemented that as singleton
[source lang="cpp"]class IceSpear;
class FireBall;
class Sprint;
class Teleport;[/source]
And to use one of the skill
[source lang="cpp"]character.doSkill(Fireball::getInstance());[/source]

I know I shouldn't use singletons a lot. How can I avoid this?
An invisible text.
Advertisement
Is there a reason Fireball needs to be a singleton and you can't just do
character.doSkill(new Fireball());
The reason I decided to use singletons is that there's going to be only one instance of Fireball at all times and rather than calling new and delete, I thought it would be better to just make it singleton

wait.. I just got an idea that forced me not to use singleton.
thanks, anyways.
An invisible text.
yeah... you could just use a const to record the maximum number of fireballs, and a static member variable to record the current number of fireballs, and set the max at 1 and use a factory to instantiate a fireball which checks to see if the maximum number of fireballs has been reached before allocating memory for another instance... (totally off the top of my head, so don't trust me)

The main reason singletons are bad is because they're pretty much like publicly accessible global variables. If joe down the hallway decides that he wants to use your singleton and he mucks around with some internal variable values in his code and then you muck around in some other code which mucks around with internal variables, you're going to run into some dependency issues which will inevitably manifest themselves as bugs which are really hard to track down. Or, you'll develop your code around the assumption that the singleton is always going to be the lone instance, but five weeks later, your boss/customer/good idea fairy comes down and says "yeah... we want more than one fireball." and that's going to cause some serious refactoring of code. If you use singletons, expect to be up to your knees in muck, stumbling around and mumbling "fuck."

Just.... entirely forget what a singleton is. Erase it from memory.

The reason I decided to use singletons is that there's going to be only one instance of Fireball at all times and rather than calling new and delete, I thought it would be better to just make it singleton

wait.. I just got an idea that forced me not to use singleton.
thanks, anyways.

When you come up with a solution to a problem you've asked about, please post that solution. Someone in the future may search for something related, find your post, and just see "nevermind, I figured it out", which is frustrating. You're not helping anyone by not posting it. Posting your idea may also spur more discussion that leads to even better ideas.
I know I shouldn't use singletons a lot. How can I avoid this?

You can use a factory, then pass the factory around:


class Factory {
private:
map<string,Entity*> prototypes;

public:

Entity* create(const string&amp; name) {
if ( prototypes[name] )
return prototypes[name];
}

// Or:
// template<class T>
// T* create() { }
// template<> Fireball* create() { return (Fireball*)prototypes["fireball"] /*or etc...*/; }
};

struct Game {
Factory f;
};

void test( Character&amp; c, Factory&amp; f ) {
c.doSkill(f.create("fireball"));
// or: f.create<Fireball>()
}

Or etc...

You can also use const char* over std::string if you need to avoid frequent memory allocations there..
<p>[quote name=&#39;Suspense&#39; timestamp=&#39;1352138362&#39; post=&#39;4997648&#39;]<br />
[quote name=&#39;lride&#39; timestamp=&#39;1352049360&#39; post=&#39;4997226&#39;]<br />
The reason I decided to use singletons is that there&#39;s going to be only one instance of Fireball at all times and rather than calling new and delete, I thought it would be better to just make it singleton<br />
<br />
wait.. I just got an idea that forced me not to use singleton.<br />
thanks, anyways.<br />
[/quote]<br />
When you come up with a solution to a problem you&#39;ve asked about, please post that solution.  Someone in the future may search for something related, find your post, and just see &quot;nevermind, I figured it out&quot;, which is frustrating.  You&#39;re not helping anyone by not posting it.  Posting your idea may also spur more discussion that leads to even better ideas.<br />
[/quote]<br />
<br />
I could make fireball of different sizes, but to do that, I should construct multiple instances of fireball each containing different size info</p>
<pre>
[source lang=&quot;cpp&quot;]character.doSkill(new Fireball(3)) //3 is the size[/source]</pre>
An invisible text.

The main reason singletons are bad is because they're pretty much like publicly accessible global variables.
...
Just.... entirely forget what a singleton is. Erase it from memory.


I often see this statement, but I don't understand it, so please help me understand. That is, I believe I understand the problem of using global variables.

A problem with types is that they are (usually) global. That is, if there is a class defined in a header file, someone can include that header file and instantiate an object from it. This could lead to errors if the class manages a resource that there only should be one instance of. Using the singleton design pattern will guarantee that there can only be one instance.
[size=2]Current project: Ephenation.
[size=2]Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/
Whats wrong with creating a Fireball instance and passing a const ref or pointer?

game.init(){
.....
.....
fireball= new Fireball()
character= new Character();
}

game.iteration(){
.....
.....
character.doSkill( fireball)
}
Why does there need to be a concrete Fireball class anyway? A fireball is just a projectile with an exploding component that does fire damage. Object composition is your friend. By creating concrete classes like that, you limit your options and make a lot more work for yourself in trying to shoehorn everything in. What if you want an Iceball spell? You could create an Iceball class, duplicate some code from Fireball and change some things around, or inherit from a base class... but all of that is a code smell that ultimately leads you into a bad place of spaghetti code that can kill your project. Why not construct a composition system, instead? Break it down into individual behaviors, and add those behaviors to an object as it needs them.
Here is the gist of how I construct a fireball spell in Goblinson Crusoe:

1) Create an Object. An Object is an empty canvas; at this point, it could be anything.
2) Add a projectile component. Now, the object is a thing that moves from one place to another, and when it gets where it's going or hits something along the way, it sends itself a message that it has collided. It listens for logic update messages to know when to move. Lots of spells would share this component: fireball, ice spear, thrown rock, shot arrow, etc...
3) Add an animation component. Now, the projectile has a visual presence in the world, a looping animation of a fireball streaking through the air. Lots of spells would share this component, too.
4) Add an explosion damage payload. This component listens for the notification that is has collided with something, and when it receives such a message it will query the world for all other objects within a specified radius, and deliver a packet of Fire damage to each one. Some spells might use this area-effect payload, others might use a single-target-damage payload. Others might use a heal-target payload, or a heal-area payload. Still others might use a polymorph-other payload. Whatever; this component describes what happens when the thing hits something.
5) Add a Flash component, which also listens for a collided notification and spawns an explosion animation.
6) Finally, add a terminator component that also listens for collided, and sends the object a message to die.

At any step along the way of constructing this object, you can tweak things. Change the damage type to Ice and the animations to iceball and ice explosion. Add a component that spawns additional projectiles for damage debris or ember shards that strike additional enemies. Add a component that spawns 100 little floating daisies to settle out of the fire-seared air onto the scorched earth. Change the projectile component type to tracking rather than straight-line, in order to hunt down and destroy. Change the Flash animation to a nuke going off, for extra visceral effect. You name it. You are not limited to just one generic type of fireball. And there are no singletons to be seen anywhere in that scenario.

This topic is closed to new replies.

Advertisement