C # simple factory Model

Source: Internet
Author: User

Using the design pattern can make ourCodeIt is more flexible, easier to expand, and easier to maintain. Various object-orientedProgramThe 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.

Let's look at an example:

My program needs a series of objects, such as Apple, orange ..., To use them, we must generate them in the program based on user requirements and call the new operator one by one so that the client program will know the information of the corresponding class, the generated code is obviously not flexible enough. We can not use specific classes in the code, but simply describe what we need, and then we can get the object we want?

Oh, we all look at the design patterns. Let's listen. Many people are there preaching how they are doing well. Let's look at how to use them to solve the problem. If the goal is clear, let's see which one meets our requirements. I have read all of gof's "design patterns", but I have read some of them clearly. So let's see if we can "Get together? J: Well, our program considers how to create objects. The creation mode should meet the requirements. Then let's look at the "intention" section of each model. Haha, the first one seems to have hit the color. Let's take a look at the abstract factory. "It provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes ", at least "no need to specify their specific classes" meets our requirements. Let's take a look at its structure:

 

Our problems don't seem to be so complicated. Only orange, apple, and so on (should be the product). They are obviously one type, all of which are fruit, we only need a factory that produces fruit. The inheritance hierarchy on the left is not. There is only one fruitfactroy. Don't worry about it. It's just practical. j

The following things are clearly what we need:

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! ");
}
}

What should we do with our fruitfactory? In the above structure diagram, it gives createproducta. Well, I will make orange, and there is a createproductb. Isn't makeorange enough ??

Public class fruitfactory
{
Public orange makeorange ()
{
Return new orange ();
}
Public Apple makeapple ()
{
Return new Apple ();
}
}

How can we use this factory? Let's write down the following code:

String fruitname = console. Readline ();
Ifruit myfruit = NULL;
Fruitfactory myfruitfactory = new fruitfactory ();

Switch (fruitname)
{
Case "orange ":
Myfruit = myfruitfactory. makeorange ();
Break;
Case "apple ":
Myfruit = myfruitfactory. makeapple ();
Break;
Default:
Break;
}

Compile and run the program, and enter what you want on the console. Immerse yourself in happiness.

But wait, it seems not perfect. If I want pear, I need to add judgment in the switch in the Customer Code and the makepear method in the factory method. Better, only one method is provided in the factory, makefruit, and then a parameter name is passed to represent the name of the desired fruit. In this case, it seems that the switch in our customer code can be avoided. On the contrary, it seems that one is needed in fruitfactory. What are you waiting? .

Fruitfactory:
Public class fruitfactory
{
Public ifruit makefruit (string name)
{
Switch (name)
{
Case "orange ":
Return new orange ();
Case "apple ":
Return new Apple ();
Default:
Return NULL;
}
}
}

Customer Code:

String fruitname = console. Readline ();
Ifruit myfruit;
Fruitfactory myfruitfactory = new fruitfactory ();
Myfruit = myfruitfactory. makefruit (fruitname );

This looks much better. At least I should not write a long string of judgment code in the Customer Code.

Ah Q is working again, and we are immersed in the joy of success. Well, the Code seems to be okay and there should be no improvement. However, another voice says:

"Except a little ......"

"Well? Wait, what ?"

"Fruitfactory also has a switch. It looks like it's also ugly !"

"Hum, it must have been" refactoring "or" TDD ". How is the requirement so harsh! I am also idle. Can I change it ?"

Since there is no conditional judgment, only the fruit name is passed in. For example, if name = "apple" is used to generate an apple object, I need new Apple (). If I can: new makeittoclass (name) converts a string into a class. C # does not have the above syntax, but provides the corresponding mechanism, that is, reflection. An important class is the system. Type class, which plays a core role in reflection. We can use the method, field, attribute, and nested class of the type object to find all information about the type.

Another important class is system. activator, which contains specific methods for creating object types locally or remotely, or obtaining references to existing remote objects.

We can first use the type class to obtain the type information of the class name specified by name, and then use activator to create an object based on this information. What are you waiting?

Public class fruitfactory
{
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;
}
}

After such processing, we do not need to modify the customer code when adding new fruits, and the factory Code does not need to be modified. How can this be done!

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.