Sunday, February 7, 2010

Design Problem - Share the Common Instance of Base Class



Here is the problem statement (might sound weird):

I one of my previous project, one guy asked me the solution of a problem. And the problem was:

“Class A and B are child class of Base i.e. ‘A’ and ‘B’ are derived from ‘Base’ Class. Now Base class containing some reference of the other utility classes which are supposed to be common across A and B. So, I want to use the single instance of class Base class. When I am creating instance of any child class (say A), it’s instantiating Base class and its utility objects. After this, when I am creating the instance of class B, again it’s instantiating class B and its utility objects which I WANT TO STOP.[see image BaseClassStructure.jpg]

There was no definite sequence of initialization of child classes.

When I looked @ the base class, I was surprised by the design of the classe. Only correct thing was the name of the Base class J (it was serving its purpose). Base class was not serving any purpose as a parent class. I recommended to change the design. Instead of inheritance, I recommended association of Base class with A and B. [see image IndependentClassStructure.jpg]

Few points about the problem:

· Initially that guy was not agree to change the design. So, he asked me to tell me a way to implement this.

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.

Any idea when such type of design/ implementation will be useful?

Here is the implementation:

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