What is a hook method?

4

I'm studying some design patterns and I came across this method, but its concept was not clear to me. What does the method do and what is the relationship between it and the Template Method?
I would like an example in java. Excerpt that I did not understand:

  

hook methods are methods that allow extension.   The superclass has a main public method that is invoked by its clients.   This method delegates part of its execution to the hook method, which is an abstract method that must be implemented by the subclass ...

    
asked by anonymous 23.02.2016 / 17:50

2 answers

7

These methods hook are used in the Template template. Just like the excerpt you mentioned mentions, there is an abstract class A that delegates parts of its functionality to abstract methods. A concrete% class of% inheriting from this class must implement these methods for the code to compile. Here's an example:

public abstract class MinhaClasseAbstrata {
    public abstract int porcaoPersonalizada(String parametro);

    public int acaoPrincipal(String parametro) {
        return parametro.length() + porcaoPersonalizada(parametro);
    }
}

public MinhaClasseConcreta extends MinhaClasseAbstrata {

    public int porcaoPersonalizada(String parametro) {
        return parametro.length() + 55; // um cálculo qualquer específico para esse caso
    }

}


public MinhaOutraClasseConcreta extends MinhaClasseAbstrata {

    public int porcaoPersonalizada(String parametro) {
        return parametro.length() + 23; // um cálculo qualquer específico para esse caso
    }

}

In this way, you know that you can call B on any copy of class acaoPersonalizada that there will be a return, based on the definition of MinhaClasseAbstrata of the concrete type of the object in question.     

23.02.2016 / 18:16
5

The "Hook Method" acts as a placeholder within "Template Method".

This means that it is a method declared in the base class, but is only defined in derived classes.

Take a closer look at this link, which explains about the Template Method Pattern: link

    
23.02.2016 / 18:10