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

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

    Or, if you want to go really fancy, invert control: Have the class return the factory, and instrument the factory with a delegate that can create the class.

    public class BusinessObject
    {
      public static BusinessObjectFactory GetFactory()
      {
        return new BusinessObjectFactory (p => new BusinessObject (p));
      }
    
      private BusinessObject(string property)
      {
      }
    }
    
    public class BusinessObjectFactory
    {
      private Func _ctorCaller;
    
      public BusinessObjectFactory (Func ctorCaller)
      {
        _ctorCaller = ctorCaller;
      }
    
      public BusinessObject CreateBusinessObject(string myProperty)
      {
        if (...)
          return _ctorCaller (myProperty);
        else
          return null;
      }
    }
    

    :)

提交回复
热议问题