gpt4 book ai didi

.net - .NET Framework 中的构造函数与工厂

转载 作者:行者123 更新时间:2023-12-01 08:04:49 26 4
gpt4 key购买 nike

下面是一篇关于.net framework对模式的使用的文章。我不确定我是否理解下面摘录中的粗体部分。这是否意味着如果您更改创建对象的细节,您(可能)会更改构造函数参数?

There are many cases in the Framework where you can obtain a new instance of a struct or class without calling its constructor yourself. The System.Convert class contains a host of static methods that work like this. To convert an integer to a Boolean, for example, you can call Convert.ToBoolean and pass in the integer. The return value of this method call is a new Boolean set to "true" if the integer was non-zero and "false" otherwise. The Convert class creates the Boolean for you with the correct value. Other type conversion methods work similarly. The Parse methods on Int32 and Double return new instances of those objects set to the appropriate value given only a string.

This strategy for creating new object instances is known as a Factory pattern. Rather than invoking the object's constructor, you can ask the object factory to create the instance for you. That way, the factory class can hide the complexity of object creation (like how to parse a Double out of a string). If you wanted to change the details of creating the object, you'd only have to change the factory itself; you would not have to change every single place in the code where the constructor is called.

发件人:http://msdn.microsoft.com/en-us/magazine/cc188707.aspx .

最佳答案

我实际上认为他们提供的示例不一定是很好的示例。

当您构造类时,工厂模式在 .NET 中变得更加有用。例如,查看 WebRequest class .

这个类通常通过调用来实例化:

WebRequest request = WebRequest.Create(url);

WebRequest.Create方法使用工厂模式。根据 URL 的类型,它会创建不同类型(子类)的 WebRequest。例如,如果您向它传递一个 http:// url,您实际上会创建一个 HttpWebRequest。实例 - ftp:// URL 将创建一个 FtpWebRequest .

通过在此处使用工厂模式,以后可以添加更多 URL 类型,而无需更改客户端的任何代码 - 您只需传入不同的 URL(作为字符串),并获得一个新对象。

关于.net - .NET Framework 中的构造函数与工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1869519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com