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

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

    After so many years this got asked, and all the answers I see are unfortunately telling you how you should do your code instead of giving a straight answer. The actual answer you were looking for is having your classes with a private constructor but a public instantiator, meaning that you can only create new instances from other existing instances... that are only available in the factory:

    The interface for your classes:

    public interface FactoryObject
    {
        FactoryObject Instantiate();
    }
    

    Your class:

    public class YourClass : FactoryObject
    {
        static YourClass()
        {
            Factory.RegisterType(new YourClass());
        }
    
        private YourClass() {}
    
        FactoryObject FactoryObject.Instantiate()
        {
            return new YourClass();
        }
    }
    

    And, finally, the factory:

    public static class Factory
    {
        private static List knownObjects = new List();
    
        public static void RegisterType(FactoryObject obj)
        {
            knownObjects.Add(obj);
        }
    
        public static T Instantiate() where T : FactoryObject
        {
            var knownObject = knownObjects.Where(x => x.GetType() == typeof(T));
            return (T)knownObject.Instantiate();
        }
    }
    

    Then you can easily modify this code if you need extra parameters for the instantiation or to preprocess the instances you create. And this code will allow you to force the instantiation through the factory as the class constructor is private.

提交回复
热议问题