Constructor vs. Factory in .NET Framework

前端 未结 4 1100
长发绾君心
长发绾君心 2021-01-23 01:22

Below is an article about .net framework\'s use of patterns. I\'m not sure I understand the bolded part in the excerpt below. Is it implying if you change the details of creati

4条回答
  •  梦毁少年i
    2021-01-23 01:59

    The Factory Pattern is the one that I use the most on my programs. It can be very helpful on certain cases, but you should certainly be careful when using it. If your factory looks like a constructor overload, then it probably should be a constructor overload. The examples that were given by the MSDN article aren't good. In fact, it has been my belief for quite some time that objects like Int, String, etc., don't contemplate overloads for each other because they are structs rather than classes and, as a rule, struct constructors should not throw exceptions (which would happen if, for example, you could feed a "hello world" to a int). But I assumed that.

    There are, of course, lots of place around the web where you can find better explanations of when to use the factory pattern and its benefits. The example given by Reed is one of the best and follows my rule for using Factories: I use factories when I have a class hierarchy or a number of classes that implement a certain interface and I want to build one of those objects but receive an object of the superclass/interface rather than the object itself. That way, the object that's calling the factory doesn't have to worry about implementation details. It knows that it's expecting an object of a certain class, and that's what it gets, even if it's a cast.

    In the current application I'm building (a program generator), I need to parse a datatable SQL definition. I use a home-brew parser to do that. Each time the parser encounters a variable ("IDENTIFIER VARIABLE-TYPE"), I call a factory and pass the string to it. The factory then checks the variable-type substring and returns to me a SqlVariable, that could actually be an IntegerSqlVariable or a CharSqlVariable.

    The main parser object doesn't know what variable it got. It pushes the SqlVariable to a list and reads the next line. Of course, I could have a single class to deal with all variable types; I personally choose not to do so.

提交回复
热议问题