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

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

    Would appreciate hearing some thoughts on this solution. The only one able to create 'MyClassPrivilegeKey' is the factory. and 'MyClass' requires it in the constructor. Thus avoiding reflection on private contractors / "registration" to the factory.

    public static class Runnable
    {
        public static void Run()
        {
            MyClass myClass = MyClassPrivilegeKey.MyClassFactory.GetInstance();
        }
    }
    
    public abstract class MyClass
    {
        public MyClass(MyClassPrivilegeKey key) { }
    }
    
    public class MyClassA : MyClass
    {
        public MyClassA(MyClassPrivilegeKey key) : base(key) { }
    }
    
    public class MyClassB : MyClass
    {
        public MyClassB(MyClassPrivilegeKey key) : base(key) { }
    }
    
    
    public class MyClassPrivilegeKey
    {
        private MyClassPrivilegeKey()
        {
        }
    
        public static class MyClassFactory
        {
            private static MyClassPrivilegeKey key = new MyClassPrivilegeKey();
    
            public static MyClass GetInstance()
            {
                if (/* some things == */true)
                {
                    return new MyClassA(key);
                }
                else
                {
                    return new MyClassB(key);
                }
            }
        }
    }
    

提交回复
热议问题