make sure object only created by factory (C#)

前端 未结 8 1560
梦谈多话
梦谈多话 2021-01-18 11:03

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

EDIT: I need the factory

相关标签:
8条回答
  • 2021-01-18 11:51

    Make the constructor internal and house the factory in the same assembly.

    public MyClass
    {
        internal MyClass()
        {
        }
    }
    

    in same assembly

    public MyClassGenerator
    {
        public static CreateMyClass()
        {
            return new MyClass();
        }
    }
    

    If the factory can't be in the same assembly or this method doesn't work for you, look to Dan's answer

    0 讨论(0)
  • 2021-01-18 11:58

    It will always be created by calling new somewhere, but if you only want that to happen in your factory class, you can set all the constructors to Internal (or Private, and use a Public Static factory method on the same class).

    0 讨论(0)
提交回复
热议问题