Templated Method - Is it possible to implement with composition instead of inheritance?

5
To create a Thread we can either extend the Thread class and override the run() method, such as having a class that implements the Runnable , implement the run() method and pass the reference of an object of this class that we created as an argument to the Thread constructor.

Looking at the code of the start() method, it makes a call to the run() method that could be interpreted, in my opinion, as a step for the execution of the start() method of Thread .

Would it be possible to apply the template method using composition?

Could the class Thread of the java.lang package be seen as a good example of this pattern using composition?

Given the definition of pattern :

  

Defines the skeleton of an algorithm in an operation, letting subclasses complete some of the steps.

Would it be possible to state what was stated above?

    
asked by anonymous 24.04.2016 / 20:15

1 answer

1

Yes it is possible, and it has advantages to implement in the template method.

The advantages are:

  

1st is implemented simply by forwarding all calls to an object field.

     

2nd has no dependency on implementation details.

     

3rd is more flexible, since it is dynamically defined at runtime, not statically at compile time.

     

4th Easy to read.

     

5º Easy to test (there are no abstract classes and all dependencies are declared directly).

But while there are advantages, there are also disadvantages, such as:

  

1st Dependencies should be managed directly by getters or in the constructor

     

2nd It's a lot less intuitive at first, and if you're used to it otherwise, it will be more complicated to get used to the code.

     

3rd is not very detailed with respect to the use of inheritance

And one of the rules of object orientation is:

  

"Favor the composition of objects over inheritance of classes. For once you use class inheritances, use becomes excessive because of reuse of codes. If you use object composition, you will apply one time or another in design patterns "

To learn more about, take a look here:

link

link

link

link

link

    
16.06.2016 / 18:59