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

后端 未结 17 1742
小鲜肉
小鲜肉 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:26

    Apart from what Jon suggested, you could also either have the factory method (including the check) be a static method of BusinessObject in the first place. Then, have the constructor private, and everyone else will be forced to use the static method.

    public class BusinessObject
    {
      public static Create (string myProperty)
      {
        if (...)
          return new BusinessObject (myProperty);
        else
          return null;
      }
    }
    

    But the real question is - why do you have this requirement? Is it acceptable to move the factory or the factory method into the class?

提交回复
热议问题