c# - 使用通过私有(private)构造函数返回新实例的静态方法有优势吗?

标签 c# static constructor private

我偶尔看到的模式是这样的:

public class JustAnotherClass
{
    private JustAnotherClass()
    {
        // do something
    }

    static JustAnotherClass GetNewClass()
    {
        return new JustAnotherClass();
    }
}

为什么这会比仅拥有公共(public)构造函数更有优势?

最佳答案

Why would this ever give an advantage over just having a public constructor?

这是一个工厂模式。您有一个创建这些实例的点。

优点是在将来的扩展中您可以添加逻辑,例如返回派生类实例。或者在某些条件下返回null。构造函数不能返回 null

关于c# - 使用通过私有(private)构造函数返回新实例的静态方法有优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12671732/

相关文章:

c# - 在 ASP.NET MVC 中创建数据库回调的最有效方法

c - 如何在多个模块中处理静态全局变量?

c# - 从基本 Delphi 窗体派生 C# 窗体

c# - 为什么我的 Azure AD 身份验证在登录时显示 "The system cannot find the file specified"错误?

c# - 将值转换为类型的 JSON 错误

c++ - 如果我从不调用这个方法,我可以把 static_assert 放在类方法中吗?

c# - 在构造函数中调用异步方法?

java - C++ this 在构造函数中?

c# - 以编程方式将 Windows 服务添加到 Windows 防火墙(安装期间)

模板函数内的 C++ 静态变量初始化