Composition Inheritance

The advantages of using composition over inheritance are well known;

When is the opposite preferable?

In practice, I see the advantage of forcing the base constructor, but I would like to know the opinions of other people about other cases / domains.

+4
source share
4 answers

The only advantage of inheritance over the composition that I can think of is that it can potentially save you from a lot of delegation of the boiler plate.

If you really have an is-a relationship and you just want to use all the methods from the base class in your subclass, then inheritance gives you all these methods for free.

+2
source

, " " GoF.

(. 20):

.

. . , . , . , , .

, , ( ), . .

, , .

, . , , .

, , , . , , . , , . , .

, , , .

, , . . , , , . , .

, , , . , .

GoF, , Strategy Pattern, Template Method, .

, , .

Holub on Patterns, 2 , Why extends is Evil, .

.

  • . , , .
  • : , . . , , , , - , , , . , , . , . .
  • Fragile-Base-Class. - ( extends) , . " " . "", - , , , .
+1

.

AFAIK, () -, , Composition; .. ; HAS A. : EntityA EntityB. . Decorator design pattern, Composition.

Inheritance, IS A . .. EntityA A EntityB () EntityA a EntityB

0

One of the special cases when I find inheritance is the best solution when I use a class created at runtime that needs additional methods. For example (in C #):

public abstract class Rule{
    /* properties here */
    public Authorization Authorization { get; set; }
    public abstract bool IsValid(dynamic request, User currentUser);
}

Generated Template:

public class Generated_1Rule : Rule{
    public override bool IsValid(dynamic request, User currentUser){
        // the user script is here
    }
}

Example user script:

return Authorization.IsAuthorized("Module_ID_001", currentUser);

The advantage is that you can add functionality to the generated β€œcompiled” script, and it is less broken than it inherits from the interface / composition because it is compiled.

0
source

All Articles