Templated Method - Is it possible to implement with composition rather than inheritance?

Asked

Viewed 167 times

5

To create a Thread we can both extend the class Thread and overwrite the method run(), how to have a class that implements the interface Runnable, implement the method run() and pass the reference of an object of this class that we created as an argument to the constructor of Thread.

Observing the code of the method start() I saw you make a call to the method run() which could, in my view, be interpreted as a step towards implementing the start() of Thread.

It would be possible to apply the method template using composition?

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

Given the definition of Pattern:

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

It would be possible to state what was exposed above?

1 answer

1

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

The advantages are :

1º IS implemented simply by forwarding all calls to an object field.

2º No dependency on implementation details.

3º Is more flexible, as it is dynamically defined at runtime, and not statically at compile time.

4th Easy to read.

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

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

1º Dependencies must be managed directly by getters or in the constructor

2º It is much less intuitive at first, and if you are used to it otherwise, it will be more complicated to get used to the code.

3º It is not very detailed regarding the use of inheritance

And one of the rules of object orientation is :

"Favor the composition of objects over class heritages. Because once you use class inheritances, you use them too much because of code reuse.If you use object compositions, you’ll apply them once in a while to design patterns"

To learn more about, take a look here :

http://www.javapractices.com/topic/TopicAction.do?Id=72

https://fillumina.wordpress.com/2012/03/09/comparison-between-composition-and-template-pattern/

https://docs.oracle.com/javase/7/docs/api/java/lang/package-summary.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

http://www.javapractices.com/topic/TopicAction.do?Id=164

Browser other questions tagged

You are not signed in. Login or sign up in order to post.