Here is the problem statement (might sound weird):
There was no definite sequence of initialization of child classes.
I tried for sometime, but I could not stop the initialization of base class on child class instantiation. I was really wondering if there is any way to do this. I was failed to provide the code to support the design
(though bad)
· Today I was going through singleton implementation and suddenly I got one idea to implement the above discussed design.
Check Program.cs. [Here, Utility is class ‘Use’]
Still I am not sure when any one will go for such design.
public class Program
{
public static void Main()
{
ChildSengleton obj1 = new ChildSengleton();
Child2Sengleton obj2 = new Child2Sengleton();
obj1.PrintCount();
obj2.PrintCount();
}
}
class Use
{
public static int count = 1;
public Use()
{
count++;
}
public int Count
{
get { return count; }
}
}
public class Singleton
{
private static Singleton instance = new Singleton(1);
private Use useobj;
protected Singleton()
{
}
private Singleton(int count)
{
useobj = new Use();
}
public static Singleton BaseRef
{
get
{
return instance;
}
}
public int Count
{
get
{
return instance.useobj.Count;
}
}
}
public class ChildSengleton : Singleton
{
public void PrintCount()
{
Console.WriteLine(this.Count);
}
}
public class Child2Sengleton : Singleton
{
public void PrintCount()
{
Console.WriteLine(this.Count);
}
}
No comments:
Post a Comment