Factory vs instance constructors

后端 未结 10 1918
渐次进展
渐次进展 2020-12-13 17:41

I can\'t think of any reasons why one is better than the other. Compare these two implementations:

public class MyClass
{
    public MyClass(string fileName         


        
10条回答
  •  感动是毒
    2020-12-13 18:20

    Another common case where factory methods help (in languages like C# which don't support type inference from constructor) is when you have to minimize type parameter specification. Consider the common case of Tuple class. You can either do:

    new Tuple(1, 1); //constructor call
    

    or

    Tuple.Create(1, 1); //factory pattern.
    

提交回复
热议问题