make sure object only created by factory (C#)

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

    Many people have mentioned using internal, but you can also make your constructors protected and derive a class that just has the static factory method in it. This doesn't prevent others from doing the same thing, but does a pretty good job at restricting direct access to your constructors.

提交回复
热议问题