工厂VS实例构造函数 [英] Factory vs instance constructors

查看:202
本文介绍了工厂VS实例构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不出任何原因之一是优于其他。比较这两种实现方式:

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)
    {
        // some code...
    }
}

而不是:

public class MyClass
{
    private MyClass(){}

    public static MyClass Create(string fileName)
    {
       // some code...
    }
}

有在.NET framework中一些地方使用一个静态方法来创建实例。起初我想,它注册它的情况下,让他们的轨道,但正规的构造可以通过使用私有静态变量做同样的事情。

There are some places in the .Net framework that use a static method to create instances. At first I was thinking, it registers it's instances to keep track of them, but regular constructors could do the same thing through the use of private static variables.

什么是?这种风格背后的原因

What is the reasoning behind this style?

推荐答案

请注意:你有什么的的静态构造函数,这是一个创建的实例,而不是调用构造函数自己静电功能。静态构造函数是完全不同的事情。

Note: What you have is not a static constructor, it's a static function that creates the instance rather than calling the instance constructor yourself. A static constructor is a different thing entirely.

工厂模式是一个用函数(静态或不)实例化一个类型,而不是直接使用构造一个典型的例子。需要注意的是实际的实例构造函数将获得无论什么所谓,但静态功能提供间接层,允许其返回任何类型,要么是或返回类型继承的实例,而不是仅仅的实例。是的返回类型

The factory pattern is a classic example of using a function (static or not) to instantiate a type rather than using the constructor directly. Note that the actual instance constructor will get called no matter what, but the static function provides a layer of indirection that allows it to return an instance of any type that either is or inherits from the return type, rather than only instances that are the return type.

例如:

public abstract class BaseClass
{
    public static BaseClass Create(int parameter)
    {
        if (parameter == 1)
        {
            return new Class1();
        }
        else
        {
            return new Class2();
        }
    }
}

internal class Class1 : BaseClass
{
    //code here ...
}

internal class Class2 : BaseClass
{
    //code here ...
}

这允许您隐藏 1级类2 从外部组件,而还是让消费者来处理一些专门的。

This allows you to hide Class1 and Class2 from external assemblies while still allowing the consumer to deal with something specialized.

这篇关于工厂VS实例构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆