开发者

c# Factory Method and protection levels problem

I have a base class and several subclasses derived from that base class. I also have a static function in the base class that takes some parameters, and instantiates and returns an appropriate subclass based on input parameters ( my factory method.)

Now here's my problem: I want to ONLY allow instantiation of the subclasses FROM the factory method. But if I set the constructors of the 开发者_JAVA百科subclasses to be protected, the base class can't see them. Is there an access modifier I'm missing that would allow the base class to call the subclasses constructors, but not not allow any other classes to call them?

Internal doesn't look like it will work either...I want to limit access to the subclass constructors to just the base class, there are other classes in the same assembly that should be able to access the base factory method and but not directly instantiate any of the subclasses.

Hopefully there's something really simple I'm missing...

Example:

public class Base
{
    public Base CreateChild(string childType)
    {
        if(childType == "A")
            return new ChildA();
        if(childType == "B")
            return new ChildB();

        return null;
    }
}

public class ChildA
{
    protected ChildA() // This doesn't work, since now base class can't call this!
    {
    }
}

public class ChildB
{
    protected ChildB()
    {
    }
}


You can declare the child classes as private nested classes inside Base


Have you tried declaring the child classes within the base class?

public class Base {
    protected class ChildA {}
    protected class ChildB {}
}


If accessing any derived object through the base type is a valid scenario (let's say derived types only override base implementations and do not add new functionality) then the proposed solution of making the derived types nested private classes (as previous answers propose) is the best solution.

If that's not the case then I think you are falling into a case of unjustified complexity. What is the reason why code from your same assembly can not access ChildA and ChildB constructors? It is after all code you can control, so you can always choose to make / enforce via code review that he initalization is through the factory method.

I understand there is valid reasons to not let external assemblies freely instantiate objects except through a tightly controlled mechanism. In this case just marking the constructors as internal would do.

Otherwise, I'm not sure you can achieve what you are pretending without creating a specific assembly just for this base class and its derived classes. There is definitely no access modifier that would make a static method in a derived class only visible from it's base class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜