• Create Account

## How to avoid singleton

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

10 replies to this topic

### #1lride  Members

Posted 04 November 2012 - 11:00 AM

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.

### #2zacaj  Members

Posted 04 November 2012 - 11:09 AM

Is there a reason Fireball needs to be a singleton and you can't just do
character.doSkill(new Fireball());

### #3lride  Members

Posted 04 November 2012 - 11:16 AM

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.

Edited by lride, 04 November 2012 - 11:18 AM.

An invisible text.

### #4slayemin  Members

Posted 05 November 2012 - 11:46 AM

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.

### #5Suspense  Members

Posted 05 November 2012 - 11:59 AM

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.

### #6fastcall22  Moderators

Posted 05 November 2012 - 12:07 PM

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..

Edited by fastcall22, 05 November 2012 - 12:08 PM.

zlib: eJzVVLsSAiEQ6/1qCwoK i7PxA/2S2zMOZljYB1TO ZG7OhUtiduH9egZQCJH9 KcJyo4Wq9t0/RXkKmjx+ cgU4FIMWHhKCU+o/Nx2R LEPgQWLtnfcErbiEl0u4 0UrMghhZewgYcptoEF42 YMj+Z1kg+bVvqxhyo17h nUf+h4b2W4bR4XO01TJ7 qFNzA7jjbxyL71Avh6Tv odnFk4hnxxAf4w6496Kd OgH7/RxC

### #7lride  Members

Posted 05 November 2012 - 01:14 PM

<p>

<br />

<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 />

<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 />

<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>

Edited by lride, 05 November 2012 - 01:30 PM.

An invisible text.

### #8larspensjo  Members

Posted 07 November 2012 - 09:03 AM

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.
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

### #9Aliii  Members

Posted 07 November 2012 - 10:09 AM

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)
}

### #10JTippetts  Moderators

Posted 07 November 2012 - 10:51 AM

POPULAR

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.

### #11Khatharr  Members

Posted 09 November 2012 - 03:43 AM

If you're okay with pre-loading all the resources associated with all the skills then why not just store them as resources with some kind of reference table and then create a skill class that manages any and all skills by referencing the table?

....

Now that I'm thinking about it, what are you actually talking about? Can you post or explain one of these classes? Are these classes that describe the skill's attributes or level, or are these classes that execute the skill?

Edited by Khatharr, 09 November 2012 - 03:48 AM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.