让只能通过工厂创建对象肯定(C#) [英] make sure object only created by factory (C#)

查看:158
本文介绍了让只能通过工厂创建对象肯定(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确保某一类只能通过工厂实例化,而不是通过调用直接?

How do I make sure that a certain class is only instantiated by a factory and not by calling new directly?

编辑:我需要的工厂是(依赖注入的目的)一个单独的类,所以我不能让它被实例化类的静态方法,所以我不能让私人

I need the factory to be a separate class (for dependency injection purposes) so I can't make it a static method of the class to be instantiated, and so I can't make new private.

推荐答案

如果由于某种原因,你需要的工厂和构造类是在单独的程序集(这意味着简单地使用内部将无法正常工作),你可以确保你的工厂都有机会先运行,你可以这样做:

If, for some reason, you need the factory and the constructed class to be in separate assemblies (which means simply using internal won't work), and you can ensure that your factory gets a chance to run first, you can do this:

// In factory assembly:

public class Factory
{
    public Factory()
    {
        token = new object();
        MyClass.StoreCreateToken(token);
    }

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

    private object token;
}

// In other assembly:

public class MyClass
{
    public static void StoreCreateToken(object token)
    {
        if (token != null) throw new InvalidOperationException(
            "Only one factory can create MyClass.");

        this.token = token;
    }

    public MyClass(object token)
    {
        if (this.token != token) throw new InvalidOperationException(
            "Need an appropriate token to create MyClass.");
    }

    private static object token;
}



是的,这是麻烦和尴尬。但也有可能是怪异的情况下这其实是一个很好的解决方案。

Yes, it's cumbersome and awkward. But there may be weird situations where this is actually a good solution.

这篇关于让只能通过工厂创建对象肯定(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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