Template Design Patterns

Template Design Patterns

The principle of the template design pattern: It mainly uses abstract classes to achieve code reuse effect, and interfaces are mainly used for communication contracts between modules.

 

Assumption: a certain servlet in a project needs to perform permission judgment, logging, and exception handling. We can define an abstract base class to achieve the purpose of code reuse.

 

public abstract class BaseServlet extends HttpServlet{

           public void templateMethod(){//Template method

                    // permission judgment

                    // log record

                    try{

                               doService();//Abstract method

                   }catch(XXXException e){

                            // exception handling

                   }

           }

           public abstract void doService();

}

 

The subclass inherits the parent class and implements doService().

 

Here is the difference between interface and abstract class

1. Grammatical differences

    The difference between abstract classes and ordinary classes is that abstract classes cannot create instances, have abstract methods, cannot contain abstract constructors, and abstract static methods, and others can.

    The interface method is public abstract decoration, and the variable is public static final decoration

2. Differences in design

   The interface is mainly designed for actions. For the communication contract between modules, abstract classes can realize code reuse.

 

 

Ask a question: For variables modified by final, is the reference immutable, or the value of the object that refers to the variable cannot be changed? 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326617248&siteId=291194637