make sure object only created by factory (C#)

前端 未结 8 1558
梦谈多话
梦谈多话 2021-01-18 11:03

How do I make sure that a certain class is only instantiated by a factory and not by calling new directly?

EDIT: I need the factory

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 11:47

    If, for some reason, you need the factory and the constructed class to be in separate assemblies (which means simply using internal won't work), and you can ensure that your factory gets a chance to run first, you can do this:

    // In factory assembly:
    
    public class Factory
    {
        public Factory()
        {
            token = new object();
            MyClass.StoreCreateToken(token);
        }
    
        public MyClass Create()
        {
            return new MyClass(token);
        }
    
        private object token;
    }
    
    // In other assembly:
    
    public class MyClass
    {
        public static void StoreCreateToken(object token)
        {
            if (token != null) throw new InvalidOperationException(
                "Only one factory can create MyClass.");
    
            this.token = token;
        }
    
        public MyClass(object token)
        {
            if (this.token != token) throw new InvalidOperationException(
                "Need an appropriate token to create MyClass.");
        }
    
        private static object token;
    }
    

    Yes, it's cumbersome and awkward. But there may be weird situations where this is actually a good solution.

提交回复
热议问题