Search code examples
oopinheritancedesign-patternsinterfacesingleton

Good structure for cases where only some classes in the inheritance hierarchy need certain fields or functions


I want to know a good structure for cases where only some classes in the inheritance hierarchy need certain fields or functions.

I'm creating a program with the following structure:

class Singleton
{
   public int A{get; set;}
}

class Base
{
}

class SpecialFeatured : Base
{
   protected void Common(int a){ Singleton.A = a; }
}

class A : Base {}
class B : SpecialFeatured { public void Foo(){Common(3);} }
class C : SpecialFeatured { public void Foo(){Common(4);} }
class D : Base {}
class E : SpecialFeatured { public void Foo(){Common(5);} }
class F : Base {}
...

There are specific features needed only by some classes(B, C, E), and I don't like that classes that don't need them can still access them. So, I created a SpecificFeatured class that inherits from a Base Class. However, this approach can become messy if another specific feature, like SpecificFeature2, is needed.

Also, I'm using a singleton class to store values globally for reference by multiple classes, but this structure doesn't seem ideal.

Do you have any recommended design patterns or structures? I particularly want to address the first issue. I want to avoid inheriting interfaces because each class that inherits them would need to implement the same function separately.


Solution

  • As the Gang of Four writes:

    Favor object composition over class inheritance.

    If you just need a reusable implementation of Common, why not have class that implements and exposes that behaviour, like

    public sealed class Commoner
    {
        public void Common(int a)
        {
            // Implementation goes here...
        }
    }
    

    Either just create a new instance of this class when needed, or inject it as a Strategy into classes that need it.

    If you need more special features, create other classes or methods to implement those behaviours.

    Based on the OP, it looks as though such classes doesn't even need to allow instances, but I'm suspecting that this might be an XY question.