Using the design pattern can make our Code It is more flexible, easier to expand, and easier to maintain. Various object-oriented Program The design language provides basically the same mechanism: Class, inheritance, derivation, polymorphism, and so on. However, they have their own characteristics. The reflection mechanism in C # is a very important tool, which can play a major role in practice.
Example:
Using system;
Namespace Factory
{
Public interface ifruit
{
}
Public class orange: ifruit
{
Public orange ()
{
Console. writeline ("an orange is got! ");
}
}
Public class Apple: ifruit
{
Public Apple ()
{
Console. writeline ("an apple is got! ");
}
}
Public class fruitfactory
{
Private Static fruitfactory _ instance = new fruitfactory ();
Public static fruitfactory instance
{
Get {return _ instance ;}
}
Public ifruit makefruit (string name)
{
Ifruit myfruit = NULL;
Try
{
Type type = type. GetType (name, true );
Myfruit = (ifruit) activator. createinstance (type );
}
Catch (typeloadexception E)
{
Console. writeline ("I dont know this kind of fruit, exception caught-{0}", E. Message );
}
Return myfruit;
}
}
Public class test
{
Static void main ()
{
String fruitname = console. Readline ();
Fruitfactory. instance. makefruit ("factory." + fruitname );
}
}
}
Run:
Enter: Apple to view the result