V
VidalSasoon
I have a singleton class that I want to only contain a hashtable. I want to
be able to modify this hashtable at will.
The problem I am having is each time I try to update the data using the
"SetState" method, "_Instance" keeps
on getting reset. I have a hard time grasping the idea how a singleton just
holds the data... anyway, here's
my test code for console if anyone can help.
V.
using System;
using System.Collections;
namespace test
{
class Test
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("test...");
ObjectState.SetState(3, "fork");
Console.WriteLine(ObjectState.Instance().GetState(3));
ObjectState.SetState(4, "spoon");
Console.WriteLine(ObjectState.Instance().GetState(4));
Console.WriteLine(ObjectState.Instance().GetState(3));
}
}
//Singleton....
public class ObjectState
{
private static ObjectState _Instance = null;
private Hashtable htObjects = new Hashtable();
private ObjectState(int nId, String sState)
{
htObjects.Add(nId, sState);
}
public static ObjectState SetState(int nId, String sState)
{
//if(_Instance == null)
//{
_Instance = new ObjectState(nId, sState); //<--- CONFUSION
//}
return _Instance;
}
public static ObjectState Instance()
{
return _Instance;
}
public String GetState(int nId)
{
return (String)htObjects[nId];
}
}
}
be able to modify this hashtable at will.
The problem I am having is each time I try to update the data using the
"SetState" method, "_Instance" keeps
on getting reset. I have a hard time grasping the idea how a singleton just
holds the data... anyway, here's
my test code for console if anyone can help.
V.
using System;
using System.Collections;
namespace test
{
class Test
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("test...");
ObjectState.SetState(3, "fork");
Console.WriteLine(ObjectState.Instance().GetState(3));
ObjectState.SetState(4, "spoon");
Console.WriteLine(ObjectState.Instance().GetState(4));
Console.WriteLine(ObjectState.Instance().GetState(3));
}
}
//Singleton....
public class ObjectState
{
private static ObjectState _Instance = null;
private Hashtable htObjects = new Hashtable();
private ObjectState(int nId, String sState)
{
htObjects.Add(nId, sState);
}
public static ObjectState SetState(int nId, String sState)
{
//if(_Instance == null)
//{
_Instance = new ObjectState(nId, sState); //<--- CONFUSION
//}
return _Instance;
}
public static ObjectState Instance()
{
return _Instance;
}
public String GetState(int nId)
{
return (String)htObjects[nId];
}
}
}