Search code examples
c#design-patternsarchitectural-patternsobject-oriented-analysis

What design pattern to use when I want only some derived classes to have access to a method in base class?


I have a unique problem/situation here. Trying to make it as simple as possible. I have a base class (say Parent) and a whole bunch of derived classes (say Child1, Child2 ..ChildN) directly deriving from the base class (Parent). I want to change the base class and add a "AVeryPrivilegedMethod" which will only be accessible to Child2 and Child3 and not to any other Children (or make it configurable such that in future Child5 can also use it in future, with minimal changes). What design pattern /Architectural pattern will fit this bill?

Language used - C#.

PS: I was thinking about using InternalVisibleTo but realize that this gets applied at the assembly level


Solution

  • It sounds as though you're missing another abstract class (SpecialChild for want of a better name) that inherits from Parent but from which Child2 and Child3 are derived.

                        Parent
                          | 
       |------------------|------------|----------|
    Child1            SpecialChild   Child4    Child5
                          |
             |---------------------|
          Child2                 Child3
    

    Ask yourself this question: what is different about Child2 and Child3 such that they share common behaviour themselves, but have different behaviour to all of the other children? SpecialChild models that behaviour and in the example you gave in your question would be the place to implement AVeryPrivilegedMethod.