Hi Beachboy,
Normally this can be solved with the "Parameterized Factory Pattern" as
shown in the Design patterns book.
But, your in C# (Sharp) so you can use a easier way to do this, you can
use reflection to create your class. This will require that the class
names be partly named the same as the Id you want to use to construct
the class.
There are disadvantages to this! It can make error finding harder in a
larger software project. There's so many other ways to solve this
problem as well. But this is a convient and quick way.
I think the following C# code explains what I mean. in the Main see
that you could change the string to be a different class, think of this
as your ID in your method switch (Id). When I cast to Class2 it could
be the superclass of a number of different classes each of which are
subclasses of Class2 created with the
Type.GetType("ConsoleApplication1.Class2Subclass1" ); and
Activator.CreateInstance...
using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Class2
{
public void test()
{
Console.WriteLine("Hello world");
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Type type = Type.GetType("ConsoleApplication1.Class2");
object obj = Activator.CreateInstance (type);
Class2 instanceOfClass2 = (Class2) obj;
instanceOfClass2.test();
Console.ReadLine();
}
}
}
Thanks! Philip
beachboy wrote:
My project has many class (function), it need to create a new instance each
time by the id value, how can i write a code as much simple?
Actually, all cases is doing the same thing.... , but is possible to make it
simple??? Thanks in advanced.
my code as below:
========================
switch (Id)
{
case "Class01":
com.project.util.Class01 c1 = new com.project.util.Class01();
c1.function1();
break;
case "Class05":
com.project.util.Class05 c1 = new com.project.util.Class05();
c5.function();
break;
case "Class08":
com.project.util.Class05 c1 = new com.project.util.Class05();
c8.function();
break;
}
=========================