Sign in to follow this  
Tradone

Singleton Help!

Recommended Posts

Tradone    100
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]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
what you want is a Singleton. try searching "Singleton design pattern" on google.

Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Sr_Guapo    876
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...

Share this post


Link to post
Share on other sites
Evil Steve    2017
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.

Share this post


Link to post
Share on other sites
Tradone    100
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.. )

Share this post


Link to post
Share on other sites
Gorwooken    145
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;
}

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
This might help: http://www.codeproject.com/cpp/TwoThirdsPimpl.asp

As Gorwooken stated, you do not need a singleton. If you want a global, just make a global.

If you don't place the 'extern Print print' in a univerally available header, you can somewhat limit the scope of the 'print' to only units that declare 'extern Print print' at the top of their CPP file.

But maybe that article will help you out some more in your search for truth.

Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Tradone    100
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: SINGLETON
Author: Rajesh V.S
Language: 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.

Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Tradone    100
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.



Share this post


Link to post
Share on other sites
Tradone    100
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.

Share this post


Link to post
Share on other sites
Way Walker    745
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"?)?

Share this post


Link to post
Share on other sites
Tradone    100
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!

Share this post


Link to post
Share on other sites
Tradone    100
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_H

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

Share this post


Link to post
Share on other sites
Tradone    100
before I had all the print methods of each container within that container method. for example, Cookie::Print();

now I can reorganize them all inside the Print class
Print::Cookie( std::map<std::string, std::string>& para_map )

damn, this is so cool.

Share this post


Link to post
Share on other sites
Tradone    100
Now I'm reimplementing the Algorithms class, this class is a collection of algorithms that are used throughout the whole program, most classes seem to need it, and if some of those classes don't require it, then I can simply not include the header file and don't perform a typedef on the Algorithm singleton.

:D !!!

Thanks for your advices everyone.

Share this post


Link to post
Share on other sites
Tradone    100
151# g++ -o new_shenu.cgi new_shenu.cpp Algorithms.cpp Path.cpp Cookie.cpp Parameter.cpp
/var/tmp//ccmKyJcL.o(.text+0x197): In function `main':
: undefined reference to `Print::Parameter(std::map<std::string, std::string, std::less<std::string>, std::allocator<std::pair<std::string const, std::string> > > const&)'
/var/tmp//ccmKyJcL.o(.text+0x205): In function `main':
: undefined reference to `Print::Cookie(std::map<std::string, std::string, std::less<std::string>, std::allocator<std::pair<std::string const, std::string> > > const&)'
/var/tmp//ccmKyJcL.o(.text+0x276): In function `main':
: undefined reference to `Print::Path(std::map<std::string, std::string, std::less<std::string>, std::allocator<std::pair<std::string const, std::string> > > const&)'
/var/tmp//ccmKyJcL.o(.text+0x624): In function `main':
: undefined reference to `Print::Error(std::string)'
/var/tmp//ccmKyJcL.o(.gnu.linkonce.t._ZN9SingletonI5PrintE8InstanceEv+0x18): In function `Singleton<Print>::Instance()':
: undefined reference to `Print::Print()'
/var/tmp//ccJ2h5hH.o(.text+0x25b): In function `Algorithms::ParseData(std::map<std::string, std::string, std::less<std::string>, std::allocator<std::pair<std::string const, std::string> > >&, std::string)':
: undefined reference to `Print::Error(std::string, std::string)'
151#

do you know what this means?
I'm done reorganizing by singletons, but left with these incomprehensible linking errors.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this