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

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

    So, it looks like what I want cannot be done in a "pure" way. It's always some kind of "call back" to the logic class.

    Maybe I could do it in a simple way, just make a contructor method in the object class first call the logic class to check the input?

    public MyBusinessObjectClass
    {
        public string MyProperty { get; private set; }
    
        private MyBusinessObjectClass (string myProperty)
        {
            MyProperty  = myProperty;
        }
    
        pubilc static MyBusinessObjectClass CreateInstance (string myProperty)
        {
            if (MyBusinessLogicClass.ValidateBusinessObject (myProperty)) return new MyBusinessObjectClass (myProperty);
    
            return null;
        }
    }
    
    public MyBusinessLogicClass
    {
        public static bool ValidateBusinessObject (string myProperty)
        {
            // Perform some check on myProperty
    
            return CheckResult;
        }
    }
    

    This way, the business object is not creatable directly and the public check method in business logic will do no harm either.

提交回复
热议问题