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

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

    You can make the constructor private, and the factory a nested type:

    public class BusinessObject
    {
        private BusinessObject(string property)
        {
        }
    
        public class Factory
        {
            public static BusinessObject CreateBusinessObject(string property)
            {
                return new BusinessObject(property);
            }
        }
    }
    

    This works because nested types have access to the private members of their enclosing types. I know it's a bit restrictive, but hopefully it'll help...

提交回复
热议问题