为什么要使用Create方法而不是使用“new”? [英] Why have a Create method instead of using "new"?

查看:140
本文介绍了为什么要使用Create方法而不是使用“new”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好处,什么时候使用静态构造函数?

What are the advantages and when is it appropriate to use a static constructor?

public class MyClass
{
    protected MyClass()
    {
    }

    public static MyClass Create()
    {
        return new MyClass();
    }
}

p>

and then creating an instance of the class via

MyClass myClass = MyClass.Create();

,而不是只有一个public构造函数并使用

as opposed to just having a public constructor and creating objects using

MyClass myClass = new MyClass();

我可以看到第一种方法是有用的,如果Create方法返回一个接口的实例, implements ...它会强制调用方创建接口的实例,而不是特定的类型。

I can see the first approach is useful if the Create method returns an instance of an interface that the class implements...it would force callers create instances of the interface rather than the specific type.

推荐答案

这是工厂模式,它通常可用于生成子类,但允许静态方法确定哪一个。

This is the factory pattern, and it could often be used to produce a subclass, but allow the parameters to the static method determine which one.

它也可以用于如果一个新的对象不总是需要,例如在pooling实现。

It could also be used if a new object isn't always required, for example in a pooling implementation.

如果对象的所有实例需要在创建时被缓存或注册,则也可以使用它。这确保客户不会忘记这样做。

It can also be used if all instances of the object needs to be cached or otherwise registered upon creation. This ensures that the client doesn't forget to do that.

当然,它是Singleton模式的一部分。

And of course, it is part and parcel of the Singleton pattern.

这篇关于为什么要使用Create方法而不是使用“new”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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