Analysis of Android source code design patterns and practices (15th)

Source: Internet
Author: User

Analysis of Android source code design patterns and practices (15th)
Chapter 2 template method mode

The template method pattern is the simplest behavioral design pattern, one of the most common patterns in all patterns, and is the basic technology based on inherited code reuse. In its structure, only the inheritance relationship between the parent class and the Child class exists.

1. Definition

Defines the framework of an algorithm in an operation, and delays some steps to the subclass so that the subclass can redefine some specific steps of the Algorithm without changing the structure of an algorithm.

2. Method in template method mode 1. Template Method

A template method is defined in an abstract class and combines basic operation methods to form a general algorithm or a general-line method. This template method is defined in an abstract class and completely inherited by the subclass without modification. Most template methods are definedFinal typeIndicates that the main logical functions cannot be overwritten in the subclass. The template method is a specific method, which provides a top-level logical framework, and the logical composition steps can be specific methods or abstract methods in the abstract class. Since the template method is a specific method, the abstract layer in the template method mode can only be an abstract class rather than an interface.

2. Basic Methods

(1) abstract method: an abstract method consistsAbstract class declaration, implemented by a specific subclass. Abstract keywords are used to mark abstract methods in Java.

(2) Hook method: A hook method consists of abstract classes.Declare and implementChild classes are extended. Subclass can extend the Hook method to affect the logic of the template method.

3. Use Cases

(1) Multiple subclasses have public methods, and the logic is basically the same.

(2) For important and complex algorithms, the Core algorithms can be designed as template methods, and the surrounding detailed functions are implemented by sub-classes.

(3) During refactoring, the template method is a frequently used mode, which extracts the same code into the parent class and then limits its behavior through the Hook method.

4. Simple implementation

Take a computer as an example. Suppose there are two computers, one Windows computer and one Mac computer. However, the boot process is basically the same: the steps are to turn on the power, system check, load the system, check whether you need to log on.

Abstract Computer

/*** Abstract Computer */public abstract class AbstractComputer {// The following is an abstract method, which can be overwritten by sub-classes and cannot be directly called by the outside, so use protected/*** power on */protected abstract void powerOn ();/*** check hardware */protected abstract void checkHardware (); /*** load the Operating System */protected abstract void loadOS ();/*** log on */protected abstract void login (); // The following is the hook method, declare and implement/*** logon required ** @ return true indicates logon required */protected boolean isLogin () {return true; } // The following is a template method, defined as final. The subclass cannot override this method/*** start the Computer Method to enable the power supply, system check, load the system, and check whether to log on. */Public final void startUp () {System. out. println ("-------- START --------"); powerOn (); checkHardware (); loadOS (); if (isLogin () {login ();} System. out. println ("-------- start END --------");}}

Windows System Computer (LOGIN not required ):

/*** Windows System Computer */public class WindowsComputer extends AbstractComputer {@ Override protected void powerOn () {System. out. println ("power on Windows");} @ Override protected void checkHardware () {System. out. println ("Windows computer check hardware") ;}@ Override protected void loadOS () {System. out. println ("loading Windows OS") ;}@ Override protected void login () {}@ Override protected boolean isLogin () {return false; // return false, no Logon required }}

Mac system computer (login required ):

/*** Mac System computer */public class MacComputer extends AbstractComputer {@ Override protected void powerOn () {System. out. println ("Mac power on");} @ Override protected void checkHardware () {System. out. println ("Mac computer check hardware") ;}@ Override protected void loadOS () {System. out. println ("Mac computer loading OS") ;}@ Override protected void login () {System. out. println ("Mac computer Logon ");}}

Call:

public class Client {    public static void main(String[] args) {        AbstractComputer comp = new WindowsComputer();        comp.startUp();        comp = new MacComputer();        comp.startUp();    }}

Result:

-------- Boot START -------- Windows computer power on Windows computer check hardware Windows computer load operating system -------- boot END -------------- boot START -------- Mac computer power on Mac computer check hardware Mac computer load operating system Mac computer login -------- start END --------
5. template method mode in Android Source Code 1. AsyncTask

When using AsyncTask, we all know to put time-consuming operations into doInBackground (Params... In params), if you want to perform initialization operations before doInBackground, you can write the implementation in onPreExecute. After doInBackground is executed, the onPostExecute method is executed. Instead, you only need to construct the AsyncTask object, then execute the execute method.

2. Activity Lifecycle

After the main function of ActivityThread is called, The onCreate, onStart, and onResume functions of the Activity are executed in sequence. Generally, the onCreate method is overwritten in the subclass of the Activity, in addition, setContentView is called in this method to set the layout.

6. Differences

(1) The Factory method is a special version of the template method.

(2) Both policy mode and template method mode are encapsulation algorithms. One is a combination and the other is an inheritance.

(3) The policy mode and template mode can be replaced with each other. They are all like exam papers. The policy mode is a choice question, and the template mode is a blank question.

7. Summary

The template method mode is summarized in four words: Process encapsulation. That is, a fixed process is encapsulated into a final method, and the subclass can customize some or all steps in the process. This requires the parent class to extract common code, this improves the code reuse rate and provides better scalability.

1. Advantages

(1) encapsulate the unchanged part and extend the variable part.

(2) extract some common code for easy maintenance.

2. Disadvantages

We need to provide a subclass for different implementations of each basic method. If there are too many variable basic methods in the parent class, the number of classes will increase, the system will be larger, and the design will be more abstract, in this case, the bridge mode can be used for design.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.