Using design patterns can make our code more flexible, easier to scale, and easier to maintain. Various object-oriented programming languages provide essentially the same mechanisms: classes, inheritance, derivation, polymorphism, and so on. But also have their own characteristics, C # Reflection mechanism is a very important tool, good use can play a large role in practice.
Let's take a look at an example:
My program needs a series of objects, such as Apple,orange ..., in order to use them, we must in the program according to user requirements, and then call the new operator to generate them, so that the client program to know the corresponding class information, the generated code is clearly not flexible. We can not use the specific classes in the code, but only to explain what we need, and then we can get the object we want?
Oh, we all look at design patterns, listen, a lot of people are there preaching about how good they are, and we'll see how to use them to solve the problem. The goal is clear, so let's see which one meets our requirements. Gof's "design pattern" have seen it, indefinitely to see some, then we see can not "gather" up? J Well, our program is thinking about how objects are created, and creating patterns should fit the requirements. Then we'll look at the "intent" section of each pattern. Oh, the first seems to hit the lottery, abstract factory, we look at it, "provide a set of interfaces to create a series of related or interdependent objects without specifying their specific classes", at least "no need to specify their specific classes" to meet our requirements. Let's look at the structure of it:
Our problem seems to not be so complicated, only orange,apple and so on (should be product), they are obviously a class, are fruit, we as long as a production of fruit factory can, the left side of the inheritance level, There's only one fruitfactroy to see. No, forget it. Orthodox unorthodox, practical on the line J
Some of 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 our fruitfactory be like? The above structure diagram it gives is createproducta, that good, I will makeorange, there is a CREATEPRODUCTB, I makeorange not yet??
public class FruitFactory
{
public Orange MakeOrange()
{
return new Orange();
}
public Apple MakeApple()
{
return new Apple();
}
}