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

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

    Yet another (lightweight) option is to make a static factory method in the BusinessObject class and keep the constructor private.

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

提交回复
热议问题