| re: singleton
"Avi Bercovich" <avi@sillypages.org> wrote in message
news:4013ae13$0$128$e4fe514c@dreader7.news.xs4all. nl...[color=blue]
> Jumbo[color=green]
> > "Deming He" <deming.he@worldnet.att.net> wrote in message
> > news:moFQb.10658$6O4.316338@bgtnsc04-news.ops.worldnet.att.net...
> >[color=darkred]
> >>E. Robert Tisdale <E.Robert.Tisdale@jpl.nasa.gov> wrote in message
> >>news:40130C40.6050304@jpl.nasa.gov...
> >>
> >>>Could somebody please help me with the definition of a singleton?
> >>>
> >>> > cat singleton.cc
> >>> class {
> >>> private:
> >>> // representation
> >>> int A;
> >>> int B;
> >>> public:
> >>> file://functions
> >>> const
> >>> int& a(void) const { return A; }
> >>> int& a(void) { return A; }
> >>> const
> >>> int& b(void) const { return B; }
> >>> int& b(void) { return B; }
> >>> } singleton;
> >>>
> >>
> >>Here you go...
> >>
> >>class singleton{
> >> enum {MAX_INSTANCE=1};
> >> static int num_of_instances;
> >> // representation
> >> int A;
> >> int B;
> >> public:
> >> // functions
> >> const int& a(void) const { return A; }
> >> int& a(void) { return A; }
> >> const int& b(void) const { return B; }
> >> int& b(void) { return B; }
> >>
> >> static singleton* get_a_singleton_instance();
> >>};
> >>
> >>
> >>singleton* singleton::get_a_singleton_instance()
> >>{
> >> if(num_of_instances<MAX_INSTANCE){
> >> ++num_of_instances;
> >> return new singleton;
> >> }
> >> else
> >> return null;
> >>}
> >>
> >>int singleton::num_of_instances = 0;
> >>
> >>[/color]
> >
> >
> > You can still create more than one of them i.e:
> > int main(){
> > singleton sg1;
> > singleton sg2;
> > return 0;
> > }
> >
> > I don't believe this is a singleton.[/color]
>
> I'm pretty new to C++ so I may be totally wrong, but doesn't the fact
> that num_of_instances is declared as static make sure that there is only
> one actual instance of that variable accross all possible instances of
> this singleton class?
>
> If so then the code above should work as advertised. No?
>[/color]
Well no , you are right that a static variable is global across all
instances of the class but this does not prevent us from creating loads of
instances of that class.
It only keeps count of the new instances the class creates itself.
Therefore that class can only create ONE instance with is static method but
we can create loads of insatnaces of that class. SO the class isn't a
singleton.
A true singleton works using abractation , a bit like COM. Where you cannot
create an instance directly but you can create a pointer to an interface and
then you can call on the interface to create instances. A class factory it's
sometimes known as.
I might get round to trying to post an example but don't have time right
now.I've done this before and need to refresh my memory but it's quite
advanced OOP IIRC. |