Singleton

  • Thread starter Thread starter Sathyaish
  • Start date Start date
S

Sathyaish

OK, shame on me, I can't even do a singleton properly. I have
implemented this a thousand dozen times, but I guess I've now been
awake too long.

Here's the relevant snippet. When I compile, it rightly points out that
the member _plain, in the method GetPlain(int, int) requires an object
reference. But I cannot do a this._plain in that method too because it
is a static method.

How on earth do I get out of this circle. I bet this is a trivial thing
and I have done it countless times but just now my brain is revolting.


public class Plain: IRectangularGrid, IDisposable /*It is difficult to
spell Plateau every time, so I am naming it Plain*/
{
private Plain _plain = null; /*Singleton*/

public static Plain GetPlain(POINT upperRight)
{
return GetPlain(upperRight.x, upperRight.y);
}

public static Plain GetPlain(int upperRightX, int upperRightY)
{
if (_plain == null)
_plain = new Plain(upperRightX, upperRightY);

return _plain;
}

private Plain(int upperRightX, int upperRightY)
{
//some stuff
}


My head is swirling round. Please tell me what I am missing.
 
I think you want to declare the private variable _plain as static as
well. I think this should resolve your problem, but I've been awake
for a long time too.
 
Sathyaish said:
OK, shame on me, I can't even do a singleton properly. I have
implemented this a thousand dozen times, but I guess I've now been
awake too long.

Here's the relevant snippet. When I compile, it rightly points out that
the member _plain, in the method GetPlain(int, int) requires an object
reference. But I cannot do a this._plain in that method too because it
is a static method.

How on earth do I get out of this circle. I bet this is a trivial thing
and I have done it countless times but just now my brain is revolting.


public class Plain: IRectangularGrid, IDisposable /*It is difficult to
spell Plateau every time, so I am naming it Plain*/
{
private Plain _plain = null; /*Singleton*/

public static Plain GetPlain(POINT upperRight)
{
return GetPlain(upperRight.x, upperRight.y);
}

public static Plain GetPlain(int upperRightX, int upperRightY)
{
if (_plain == null)
_plain = new Plain(upperRightX, upperRightY);

return _plain;
}

private Plain(int upperRightX, int upperRightY)
{
//some stuff
}


My head is swirling round. Please tell me what I am missing.

Hi Sathyaish,
private Plain _plain = null; /*Singleton*/

Define _plain to be static:

///
private static Plain _plain = null;
///
 
Back
Top