Factory pattern in C#: How to ensure an object instance can only be created by a factory class?

后端 未结 17 1736
小鲜肉
小鲜肉 2020-11-29 16:51

Recently I\'ve been thinking about securing some of my code. I\'m curious how one could make sure an object can never be created directly, but only via some method of a fact

17条回答
  •  被撕碎了的回忆
    2020-11-29 17:08

    I don't think there is a solution that's not worse than the problem , all he above require a public static factory which IMHO is a worse problem and wont stop people just calling the factory to use your object - it doesnt hide anything . Best to expose an interface and/or keep the constructor as internal if you can that's the best protection since the assembly is trusted code.

    One option is to have a static constructor which registers a factory somewhere with something like an IOC container.

提交回复
热议问题