Design Pattern-simple Factory pattern, design pattern factory
Warm and new, read the previous written blog "Asp.net read Excel file 2" http://www.cnblogs.com/insus/archive/2011/05/05/2037808.html think that the first piece of code example, you can use the design mode of a simple factory to achieve.
That is to say, two completely new classes are used to replace two Switch branches.
Xls class:
Xlsx class:
After this separation, the Switch code can be written as follows:
The highlighted methods above are the same. The methods of the two classes are the same. We can extract the methods of the parent class as the public method of the parent class, but Insus. net asp. NET, inheritance is rarely used, because xxx. aspx. cs has inherited System. web. UI. page, If you create another parent class to inherit, it cannot be solved, because one class can only inherit one parent class.
Therefore, we can use interfaces or abstract image classes. Class can inherit multiple interfaces or abstract classes.
The abstract class has been written, so the two classes Xls and Xlsx need to be slightly modified to implement the above abstract class FileFormat:
The same modification of Xlsx:
In the Switch block, we can change it:
The highlighted code above is what we usually call polymorphism. After the modification, we still need to write too much code on the front end. Can we write a class that specifically processes the Excel type passed in by users and directly call the corresponding class? Here Insus. NET is to say that you can write a simple factory. Directly move the Switch program to the factory class. Xxx. aspx. cs:
The code example at the beginning of this article can use this simple factory to replace the Switch method block:
The following content is added at, January 18:
One problem with a simple factory is that when a new category is added or removed, We have to modify the FileFactory class. Reflection can be used to solve this problem.Reflection.