Restrict object's creation

2019-08-24 05:24发布

问题:

I have a very strange question here. I have Class A, Class B and Class C. I want to create object of Class B which can create the object of A. But how to restrict Class C from creating object of Class A.

One way is define Class A inside Class B, so that Only Class B can create the instance of Class A and Class C cannot access Class A.

But, I think nesting is a wrong way.

Do we have any way to restrict the object creation? Is it possible to use attribute and reflection to help to restrict? If possible is there a recommended way?

Please share your thoughts. Thanks in advance.

回答1:

You can place class A and B in a single assembly and mark the constructor of class A as internal.

This way, only classes within that assembly can create instances of class A.



回答2:

You can make constructor private, and create fabric method that retuns instance of A, and parameter in this method will be instance of B.

public class A
{
  private A (){}

    public static Instance(B BInstance)
    {
       A result = null;
       if (BInstance != null)
       {
         result = new A(); 
         //create here 
       }

       return result;

    }


    }