Skip to main content
gamedev.net
🔒 Locked

Singleton Help!

Started by Tradone 23 replies 1.7k views
Original Post
Tradone
Tradone
I would like to make a global object from class Print. the object name is print, and it has some methods like print.header print.body print.tail print.cookies Thanks. [Edited by - Tradone on March 27, 2006 5:52:40 PM]
Tradone
Tradone
i went through wikipedia.
it's too complex method for me, i'm new to oop design.
i just got started with classes last week.

is there a way?
this is what my main looks like


int main(){	Print print;	Cookie cookie;	Parameter par;	par.SetFieldData();	Path path;	path.SetPath();	path.Print();....}


there is only 1 object created for all those objects above.
and only will be 1.
inside Print is a method that can be called by print.Parameter.
but I can't do that when I'm out of scope from the main {}

for example, when path.SetPath() is executed, inside the SetPath() method is a print.Error(); method. but since the print object has not been passed, ( and I can't pass it to all 30 classes ) the compiler keeps complaining.

another example, I have another class Skin,
and inside the skin object, I must somehow be able to call print.Parameter();
and print.Parameter how can this be done? Just an easy quick and dirty way using classes can do. Thanks.
kuphryn
kuphryn
In terms of scope, one solution is dynamic allocation.

Kuphryn
Tradone
Tradone
thanks.....

I need a way to pass objects automatically so that the print object automatically stays in certain listed classes.
Tradone
Tradone
you know what singleton seems to be the only alternative.
thanks.
Sr_Guapo
Sr_Guapo
Quote:
Original post by Tradone
screw it. i'm gonna pass everything manually.
thanks for the uneffort guys.


Im still confued what exactly you want... Do you want a single copy of the class shared between various other classes? If so, the only way is too use a singleton AFAIK. I personally am not too fond of singletons, so I prefer just passing pointers to objects only when thy are needed.

Also, If you want help, you are going to have to wait more than 2 hours for it...
Sean Henley [C++ Tutor]Rensselaer Polytechnic Institute
Evil Steve
Evil Steve
In some header that's included everywhere that you want to use print:
extern Print print;

In one source file:
Print print;

Just like any other global. That'll let you access print from anywhere that includes the header. However, this is a horrible thing to do. This is exactly what singletons are for, as the AP suggested.
Tradone
Tradone
yes, looks like singleton is the only way.
thanks, i'm reading the article here: http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp.

Thanks, neverk new about singleton.
and looks like it's not as complex as i thought. ( idk maybe it is.. )
Gorwooken
Gorwooken
You don't really need to use a singleton, you could just pass it like this

Just pseudo code
class Path{public:    Path(Print *print);    ~Path();    SetPath();    ....    ....    Print *m_pPrint;};Path::Path(Print *print){    m_pPrint = print;}Path::SetPath(){    ......    m_pPrint->Error();    ......}Print g_print;void main(){    Path path(&g_print);    path.Print;}


or you could just access the global from the constructor


Path::Path()
{
m_pPrint = &g_print;
}
Tradone
Tradone
is singleton supposed to be a complex technique?

well I've been out all day, and for the first 10 minutes looking through this thing i don't understand what the heck its supposed to do! damn im dumb.
Tradone
Tradone
Quote:
Original post by Gorwooken
You don't really need to use a singleton, you could just pass it like this

Just pseudo code
*** Source Snippet Removed ***

or you could just access the global from the constructor


Path::Path()
{
m_pPrint = &g_print;
}


I think I'll go with the latter.
if I go with the first, I would have to pass the print object to every single class that exists. because the print outputs the error messages, and error messages are expected to be in all classes.

but still, I don't even want to get it from the constructor if I don't have to. I want it to be there automatically, (print is not the only object like this) well I'm keep reading up on singleton, and since I have a bad background knowedge about pointers, I am trying to figure out singleton without even knowing if that would solve my problem. please somebody help me.
Tradone
Tradone
i swear, this shouldn't be so hard to do.
I just can't find the right information.

I made a class that groups all the printing functions,
now maybe my Print class should not be grouped into a class, but I did.

okay, in order to access the methods in the Print class, I can't just Print::Header() when I'm inside a Parameter Class.
I need to first declare an object, Print print;
and then print.Header(); meaning, I need to somehow make this object omnipresent in all other objects automatically.

However, I have other classes that need to use that print object, but I don't want to create a new object every time my Parameter class, Configuration class, or my 30 other objects are made. Thus I need to somehow, be able to just print.Header(); without passing anything, or doing anything of that sort. I don't know if this is possible or not, and if it's not, I would like to know the best method of doing something like this.

/*Creational Pattern: SINGLETONAuthor: Rajesh V.SLanguage: C++Email: rajeshvs@msn.com*/#include <iostream>using namespace std;class Singleton{private:    static bool instanceFlag;    static Singleton *single;    Singleton()    {        //private constructor    }public:    static Singleton* getInstance();    void method();    ~Singleton()    {        instanceFlag = false;    }};bool Singleton::instanceFlag = false;Singleton* Singleton::single = NULL;Singleton* Singleton::getInstance(){    if(! instanceFlag)    {        single = new Singleton();        instanceFlag = true;        return single;    }    else    {        return single;    }}void Singleton::method(){    cout << "Method of the singleton class" << endl;}int main(){    Singleton *sc1,*sc2;    sc1 = Singleton::getInstance();    sc1->method();    sc2 = Singleton::getInstance();    sc2->method();    return 0;}


I did some readings on singleton, and still don't get what it's supposed to do. and by looking at this source code, it doesn't really relate to my situation it seems.

Please somebody help me,
I've looked through friend classes too, and I don't think they just do it.

so I'm thinking of just doing it as an inheritance.
placing Print as the base. But that would be poor OO Design. parameters don't derive from print.
Tradone
Tradone
Quote:
Original post by Anonymous Poster
what you want is a Singleton. try searching "Singleton design pattern" on google.


I googled singleton a long time ago.
they have very simple examples, and the main thing of singletons seem to be static member variables. I need that too, but I need the print object to be omnipresent, even to those that are in separate cpp files.
Tradone
Tradone
Quote:
Original post by kuphryn
In terms of scope, one solution is dynamic allocation.

Kuphryn


not really a scope issue, I don't think I'd ever had scope issues.
Tradone
Tradone
Quote:
Original post by Sr_Guapo
Quote:
Original post by Tradone
screw it. i'm gonna pass everything manually.
thanks for the uneffort guys.


Im still confued what exactly you want... Do you want a single copy of the class shared between various other classes? If so, the only way is too use a singleton AFAIK. I personally am not too fond of singletons, so I prefer just passing pointers to objects only when thy are needed.

Also, If you want help, you are going to have to wait more than 2 hours for it...


please, help me.
Tradone
Tradone
seems like the purpose of singletons are to manage static data, I am more looking into passively passing singletons into every class without having to go through a pointer of any sort, because it would be cumbersome.

Thinking about it, I don't think this is possible, so I'm guessing the best method just might be to pass those objects through the constructor phase during the creation of an object.



Tradone
Tradone
http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-Singleton-Pattern-Part-2/1/

I found a quick and dirty solution after 2 hours of looking through the net, they explained it pretty well. :D

well, Sr_Guapo. Hopefully you can use this wealth of information.
Way Walker
Way Walker
I don't see a reason to not go with a global.

If you want some justification for not making it a singleton, just allow the user of the class to specify hich stream it should print to. This is useful and it's entirely possible you may want more than one Print object so you can print to multiple streams.

Really, "Singleton" is just a fancy name for "One and only one global instance". If everything needs access to a given instance of Print, that sounds like a job for a global. Why not make a global? Because down the line you may want different parts to print to different Print objects. Depending on exactly what you're printing, this may either be unlikely or the Print instance might easily and logically be grouped with other things you're passing around (e.g. as a member of some "world state" object).

However, I see no shame in using a global when it seems appropriate. Is the standard library poorly designed because std::cout is a global (or does tucking it in a namespace make it "less global"?)?
Tradone
Tradone
Quote:
Original post by Way Walker
I don't see a reason to not go with a global.

If you want some justification for not making it a singleton, just allow the user of the class to specify hich stream it should print to. This is useful and it's entirely possible you may want more than one Print object so you can print to multiple streams.

Really, "Singleton" is just a fancy name for "One and only one global instance". If everything needs access to a given instance of Print, that sounds like a job for a global. Why not make a global? Because down the line you may want different parts to print to different Print objects. Depending on exactly what you're printing, this may either be unlikely or the Print instance might easily and logically be grouped with other things you're passing around (e.g. as a member of some "world state" object).

However, I see no shame in using a global when it seems appropriate. Is the standard library poorly designed because std::cout is a global (or does tucking it in a namespace make it "less global"?)?


those are very powerful thoughts you put into words there.
I guess it was appropriate to use a global in that case.
But it seems like I've already implemented singleton, and I think I'm going to adventure and practice using singleton using this opportunity.

Valid Point!
Tradone
Tradone
well I was successful in implementing the singleton pattern, but I want to make it better. Please help me, for I have NO, not even a spec of backgrounds on templates and still unfamiliar with typedef with my unconventional education.
// singleton.h#ifndef __SINGLETON_H#define __SINGLETON_Htemplate <class T>class Singleton{public:  static T& Instance() {    static T _instance;    return _instance;  }private:  Singleton();          // ctor hidden  ~Singleton();          // dtor hidden  Singleton(Singleton const&);    // copy ctor hidden  Singleton& operator=(Singleton const&);  // assign op hidden};#endif// eof


okay, this is what I'm using right now.
and as described in the tutorial.

To transform the Log class from the beginning of the previous article to a singleton, without adding an Instance() function and hiding the constructor, destructor etc, I could define it this way:

typedef Singleton<Log> LOG;

And I can write to the log from any location in the application code (as long as it includes the necessary headers):

LOG::Instance().Write(“This is a logline”);

I typedef the object, and use "LOG::Instance()."
but I want to make it more convenient by somehow defining
LOG::Instance(). into just plain old log so that I can just
log.some_method();
instead of writing out the whole thing LOG::Instance().some_method();

thanks.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.