jeudi 16 juin 2016

Design Pattern: Inheritance or Composition

I have 2 classes A and B, both of which have properties X and Y; but class B also has another property, Z.

Inheritence

class A
{
    public int X;
    public int Y;
}

class B : A
{
    public int Z;
}

Class B does not have a "is-a" relationship to class A, so it breaks inheritance principals is OOP.

Composition

class A
{
    public int X;
    public int Y;
}

class B
{
    public A ObjA;
    public int Z;
}

Class B does not have a "has-a" relationship to class A so it breaks composition principals is OOP.

Without duplicate code, should I use inheritance or composition (even though they brake the principles of OOP) or is there another design pattern? I personally think that using inheritance is going to be the lesser of the evils because of readability.

Aucun commentaire:

Enregistrer un commentaire