Constructor vs. Factory in .NET Framework

前端 未结 4 1108
长发绾君心
长发绾君心 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条回答
  •  旧巷少年郎
    2021-01-23 01:47

    I actually think that the examples they've provided are not necessarily great examples.

    The Factory pattern becomes more useful in .NET when you're constructing classes. For example, look at the WebRequest class.

    This class is normally instantiated by calling:

    WebRequest request = WebRequest.Create(url);
    

    The WebRequest.Create method uses the Factory pattern. Depending on the type of URL, it will create a different type (subclass) of WebRequest. If you pass it an http:// url, for example, you will actually create an HttpWebRequest instance - an ftp:// URL will create an FtpWebRequest.

    By using the Factory pattern here, more URL types can be added later without changing any code on the client side - you just pass in the different URL (as a string), and get a new object.

提交回复
热议问题