C # application of reflection in the factory design model

Source: Internet
Author: User
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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.