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

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

    In a case of good separation between interfaces and implementations the
    protected-constructor-public-initializer pattern allows a very neat solution.

    Given a business object:

    public interface IBusinessObject { }
    
    class BusinessObject : IBusinessObject
    {
        public static IBusinessObject New() 
        {
            return new BusinessObject();
        }
    
        protected BusinessObject() 
        { ... }
    }
    

    and a business factory:

    public interface IBusinessFactory { }
    
    class BusinessFactory : IBusinessFactory
    {
        public static IBusinessFactory New() 
        {
            return new BusinessFactory();
        }
    
        protected BusinessFactory() 
        { ... }
    }
    

    the following change to BusinessObject.New() initializer gives the solution:

    class BusinessObject : IBusinessObject
    {
        public static IBusinessObject New(BusinessFactory factory) 
        { ... }
    
        ...
    }
    

    Here a reference to concrete business factory is needed to call the BusinessObject.New() initializer. But the only one who has the required reference is business factory itself.

    We got what we wanted: the only one who can create BusinessObject is BusinessFactory.

提交回复
热议问题