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

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

    Looks like you just want to run some business logic before creating the object - so why dont you just create a static method inside the "BusinessClass" that does all the dirty "myProperty" checking work, and make the constructor private?

    public BusinessClass
    {
        public string MyProperty { get; private set; }
    
        private BusinessClass()
        {
        }
    
        private BusinessClass(string myProperty)
        {
            MyProperty = myProperty;
        }
    
        public static BusinessClass CreateObject(string myProperty)
        {
            // Perform some check on myProperty
    
            if (/* all ok */)
                return new BusinessClass(myProperty);
    
            return null;
        }
    }
    

    Calling it would be pretty straightforward:

    BusinessClass objBusiness = BusinessClass.CreateObject(someProperty);
    

提交回复
热议问题