Okay, something like this may be what you are after. In my example, I've assumed that
ClassX
is the type of each cell, and it's this class that you want to lazy-initialize. By the way
ClassX
is not a singleton by definition, since you want to have multiple instances of that class. When you load up the main singleton class, call
AddCell
for every cell that you want to initialize. The underlying
ClassX
instance will not be created but we store the required arguments. Later, you can call
GetCell
to get each cell (
ClassX
instance) and it will be created on demand. So those indices that you do not access will not have their cells initialized. You can improve the interface by adding an indexer that will call
GetCell
(so it's smoother to access the cells) but that's up to you. Let me know if you have any questions.
public class ClassX
{
public ClassX(int x, int y)
{
}
}
public sealed class SingletonClass
{
private class InnerClass
{
static InnerClass()
{
}
public static readonly SingletonClass instance =
new SingletonClass();
}
private SingletonClass() { }
public static SingletonClass Instance
{
get
{
return InnerClass.instance;
}
}
const int CellCount = 100;
private ClassX[] cells = new ClassX[CellCount];
private Dictionary<int, Tuple<int, int>> paramsMap =
new Dictionary<int, Tuple<int, int>>();
public void AddCell(int index, int x, int y)
{
paramsMap[index] = Tuple.Create(x, y);
}
public ClassX GetCell(int index)
{
if (cells[index] == null)
{
if (paramsMap.ContainsKey(index))
{
cells[index] = new ClassX(
paramsMap[index].Item1, paramsMap[index].Item2);
}
else
{
throw new InvalidOperationException();
}
}
return cells[index];
}
}
[Edit]
~~~~~~~~
If you want the
GetCell
code to be thread-safe, you can change it to:
public ClassX GetCell(int index)
{
lock (cells)
{
if (cells[index] == null)
{
if (paramsMap.ContainsKey(index))
{
cells[index] = new ClassX(
paramsMap[index].Item1, paramsMap[index].Item2);
}
else
{
throw new InvalidOperationException();
}
}
return cells[index];
}
}
And what I meant by saying that
ClassX
cannot be a singleton in this scenario is that you have multiple instances of it. Perhaps you mean to say that it's a virtual-singleton for every unique set of arguments that you pass to that. If that's the case, you'd have to write code to implement that check because my code will not prevent them from adding two or more
ClassX
instances with the same parameters. I hope that makes sense.