Restrict object's creation

徘徊边缘 提交于 2019-12-25 05:16:12

问题


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;

    }


    }


来源:https://stackoverflow.com/questions/11061664/restrict-objects-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!