Hi Experts,
Please help me to find the proper way to remove the switch statement when a Interface is implement by number of classes.e.g
public enum TestClass
{
Test1,
Test2,
Test3,
Test4
}
public interface ITest
{
void Add();
}
public class Test1 : ITest
{
public void Add()
{
Console.WriteLine("I am Test1");
}
}
public class Test2 : ITest
{
public void Add()
{
Console.WriteLine("I am Test1");
}
}
public class FindObject
{
public ITest GetObject(TestClass testClass)
{
switch (testClass)
{
case TestClass.Test1:
return new Test1();
case TestClass.Test2:
return new Test2();
case TestClass.Test3:
return new Test3();
case TestClass.Test4:
return new Test4();
default:
return new Test1();
}
}
}
I above code we have interface ITest and implemented by Test1,Test2....Test4..to create the object of these classes at runtime we have method GetObject use Switch statement but I am not want to &used the switch statement.So I have tried this approach.
What I have tried:
I have used the following approach,Please suggest is it better or no.
public enum TestClass
{
Test1,
Test2,
Test3,
Test4
}
public interface ITest
{
void Add();
}
public class Test1 : ITest
{
public void Add()
{
Console.WriteLine("I am Test1");
}
}
public class Test2 : ITest
{
public void Add()
{
Console.WriteLine("I am Test1");
}
}
public class Test
{
Dictionary<TestClass, ITest> dicToTest = new Dictionary<TestClass, ITest>();
public void RegisterClass()
{
dicToTest.Add(TestClass.Test1, new Test1());
dicToTest.Add(TestClass.Test2, new Test2());
dicToTest.Add(TestClass.Test3, new Test3());
dicToTest.Add(TestClass.Test4, new Test4());
}
public ITest GetObject(TestClass testClass)
{
return dicToTest[testClass];
}
}
In above approach we have register all the class in dictionary and runtime we get the object of class on the basis of enum.
But the problem with this approach
1)When we register then class in dictionary we have to create new object (new Test1())
this we eat memory the time of registration. Is There another solution to solve this problem?.
2)Is There any generic way to solve this problem?
3)I have not used any Dependency Framework.