make sure object only created by factory (C#)

前端 未结 8 1557
梦谈多话
梦谈多话 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:45

    If the factory is in the same assembly and you only need protection against external assemblies instantiating the class, you can make the constructor internal. The only way I know to prevent this for all other classes (including those in the same assembly) is to make the instantiated class a nested private class of the factory and only expose it as an interface. If the class is its own factory (a static factory method), then you can make the constructor private, as others have mentioned.

提交回复
热议问题