Factory vs instance constructors

后端 未结 10 1920
渐次进展
渐次进展 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:26

    The factory method is often used to hide the exact type of the object being created. An abstract class can have a static factory method, which then selects the concrete derived class to instantiate depending on some condition. Only the abstract base class is publicly documented. This leaves the library supplier some freedom to change the exact type being instantiated without breaking existing code.

    An example from the .NET framework is the static factory methods on the Expression class.

提交回复
热议问题