Where should we use the template template?

Can someone tell me some examples of situations when the template template Template should be used?

Give me some real use from your own experience.

(I still found it useful only for displaying data in the DA layer. Sorry !!!)

+7
design-patterns template-method-pattern
source share
8 answers

I tried to give you examples from the real world and some common situations when a template template should be used.

  • If you want your program to be "Open For Extension", as well as "Closed for Modification". This means that the behavior of the module can be expanded so that we can make the module behave in a new and different way as the requirements of the application change or to meet the needs of new applications. However, the source code of such a module is unbreakable. No one can change the source code. In the following example, you can add a new payroll method (for example, the Remote class) without changing the previous codes.

    public abstract salary class {

    public final void calculate() { System.out.println("First shared tasks is done."); getBaseSalary(); System.out.println("Second shared tasks is done."); } public abstract void getBaseSalary(); 

    }

    public class Hourly Salary {

     @Override public void getBaseSalary() { System.out.println("Special Task is done."); } 

    }

    Public class Test {

     public static void main(String[] args) { Salary salary = .... salary.calculate(); } 

    }

  • When you come across many lines of codes that are duplicated by delaying just a few steps of your algorithm. . When you implement the content of a method or function, you may find some section of your code that varies from one type to another. A feature of these sections is that you can override or change these sections of a method or function without changing the basic structure of the algorithm (method or function). For example, if you want to solve this problem without this pattern, you will come across this example:

function0: function1: ... functionN:

 1 1 1 2 2 2 ... ... ... 5 6 n 3 3 3 4 4 4 ... ... ... 

As you can see, sectional cods 5, 6, n vary, vary from one function to another, however you have common sections, such as 1,2,3,4, which are duplicated. Let's look at a solution from one of the famous java libraries.

 public abstract class InputStream implements Closeable { public abstract int read() throws IOException; public int read(byte b[], int off, int len) throws IOException { .... int c = read(); .... } .... } public class ByteArrayInputStream extends InputStream { ... public synchronized int read() { return (pos < count) ? (buf[pos++] & 0xff) : -1; } ... } 
  • When you, as a structure developer, want your clients to simply use any executable code that is passed as an argument to your framework, which is expected to call (execute) this argument at a given time. This execution may be immediate, as with a synchronous callback, or may occur later, as with an asynchronous callback. Let's look at one of the famous ones.

    open abstract class HttpServlet extends GenericServlet implements java.io.Serializable {protected void doGet (HttpServletRequest req, HttpServletResponse resp) {...}

     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { .... doGet(req, resp); ... } ... } 

    }

    Public class MyServlet extends HttpServlet {

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //do something ... } ... 

    }

+1
source share

A template method template provides a skeleton for performing any kind of algorithm or operation and allows subclasses to redefine part of the logic.

Pros: Natural suitability for building frameworks, so that parent classes of classes can make callbacks to methods implemented in the child.

Examples:

  • java.util.AbstractList
  • Servlet doGet and doPost methods
  • MDB onMessage method
  • Struts Action Class
  • Spring data access classes

Cons: limits one inheritance in Java.

+7
source share

The use of the Template Method template has two main characteristics:

  • There is a base class (in Java, one with protected constructors only and optionally declared as abstract ) that will be subclassed in client code.
  • In the base class, two groups of methods are defined: a) one or more template methods (usually only one) and one or more primitive methods of work (usually more than one). Each template method is a high-level operation implemented in the base class in terms of primitive operations that must be implemented / redefined in each particular subclass. Typically, a template method is public and non-redefined ( final , in Java); his API documentation should determine exactly what primitive working methods he calls, and when (that is, he should describe the "algorithm"). The primitive operation method, which is a step in the algorithm, must be non-public, but redefined ( protected , in Java) and can be of two types: a) an abstract method, which must be implemented in a subclass; b) a method with a default / empty implementation that can be overridden in a subclass.

One good example in the Java 6 SDK is the execute() method of the javax.swing.SwingWorker class (this is the public final void method). In this case, the primitive working methods are doInBackground() , process(List) and done() . The first is abstract and therefore requires implementation in a subclass; it is called by the template method in the background thread. The other two have empty implementations and can be overridden in a subclass; they are called during and at the end of processing, respectively, in the EDT (Swing Event Dispatch Thread) to allow updates to the user interface.

In my own experience, I sometimes used this template. One such case was a Java base class that implements the java.util.Iterator interface, where next() was a template method, and there was only one primitive working method responsible for creating an instance of a specific domain entity class (this was intended for use in iterating over a list Permanent Domain Entity Objects Using JDBC). The best example in the same application was the base class in which the template method implemented a multi-stage algorithm designed to populate the "business object maintenance screen" (using Swing) from a specific list of persistent objects; primitive methods of operations were called: 1) clear the current state of the screen and 2) add an object in the form of a table inside the screen; optionally, other primitive operations were called from the template method, if the screen was editable.

In the end, I have to say that, although this is certainly a useful design template, the situation does not often arise when it is really applicable. Just having a base class with methods that are redefined in a subclass (a much more common situation, in my experience) is not enough in itself to qualify as a template application.

+6
source share

The most important thing in a template method is that you must define a series of abstract methods as steps or an algorithm, and let the subclass be replaced by a concrete implementation for these methods.

I applied one of the document generation programs.

 public abstract DocumentGenerator() { generateHeader(); generateBody(); generateDetails(); } public HTMLDocGenerator : DocumentGenerator() { public override generateBody() { //generate as in html format } } 

You may have another implementation, such as the csv generator of the PDF generator, and the value here is that they correspond to the algorithm (generate β†’ header, body, details).

+3
source share

A template template should be used when there is an algorithm with many implementations. The algorithm is defined in the function in the base class, and the implementation is performed by the base class and subclasses. A detailed explanation with a real-time example is given at http://preciselyconcise.com/design_patterns/templatemethod.php

+2
source share

I will draw one real world example where I used some template methods.

In the C ++ computer vision algorithm application, the algorithm behavior was designed to assume a couple of algorithm behavior options based on some parameters that were read at runtime according to the enumeration loaded into the configuration file loaded at startup. The overall skeleton of the algorithm was identical, with the exception of some key callbacks filled in the middle of what would otherwise be an identical piece of code that would be brutally duplicated to name different functions at that level. These callbacks that I wanted to use were abstracted into the base class of the template method, and the template method template prevented all code duplication. The enumeration that we used basically dictates which subclass I created the base class instance to point to this algorithm, and thus give the algorithm its associated bit of taste in behavior.

Now, some of the motivations for this variety of flavors of the operating algorithm were the stand-alone functions of the stand-alone software that controlled our tool. The introduced taste pulled out a richer debugging / diagnostic output and kept the coordinate system local to some pixels of the image, while the online taste saved things in the absolute coordinate space and supported the problems characteristic of a working tool with all its robots, and what not. Another enumeration supplanted the choice from the set of classifiers that we used for some machine learning, since different classifiers were trained under different data sets, which otherwise flow identically with the whole code, but must be interpreted differently based on some control conditions for of how that data was created.

I believe that this use case came from what was caused by a problem in the middle .

+2
source share

I used the template method for Business Logic, in which several components shared the same process, but the implementation was slightly different.

+1
source share

The Template method determines the structure of the algorithm skeleton, but discards certain steps and details into subclasses. The structure and flow of the algorithm remains static, but the details of the steps are deferred to subclasses.

I used the template method template to prepare the contents of the document. There were many different types of documents, each of which has its own small modifications. However, the basic process of preparing documents was the same for everyone.

+1
source share

All Articles