Design Mode 17-template method (behavior type)

Source: Internet
Author: User
1. Scenario Simulation

The software simulates logon control. The passwords of common users, staff users, and staff members are encrypted in the database.
The steps are as follows:
The front-end submits and the backend obtains the login information, which is compared with the login information in the database, except that the staff is encrypted and common users are not encrypted.
If yes, go to the next page. If no match exists, return to the logon page with an error message.
The Code is as follows:
Common users:

Package demo15.templatemethod. example1;/*** data model used to describe user information */public class usermodel {private string UUID, userid, PWD, name; Public String getuuid () {return UUID ;} public void setuuid (string UUID) {This. UUID = UUID;} Public String getuserid () {return userid;} public void setuserid (string userid) {This. userid = userid;} Public String getpwd () {return PWD;} public void setpwd (string PWD) {This. pwd = PWD;} public String getname () {return name;} public void setname (string name) {This. name = Name ;}} **************************************** * *************************** package demo15.templatemethod. example1;/*** data model that describes the information entered during logon by a logon user */public class loginmodel {private string userid, PWD; Public String getuserid () {return userid ;} public void setuserid (string userid) {This. userid = userid;} Public String getpwd () {re Turn PWD;} public void setpwd (string PWD) {This. pwd = PWD ;}} **************************************** * *************************** package demo15.templatemethod. example1;/*** common user logon logic processing */public class normallogin {/*** determine whether the logon data is correct, that is, whether the logon is successful * @ Param lm encapsulate the model * @ return true of the logon data, indicating that the logon is successful. False indicates that the logon fails */Public Boolean login (loginmodel lm) {// 1: obtain the information of the logon user from the database, that is, obtain the user data usermodel um = this according to the user number. findu Serbyuserid (LM. getuserid (); // 2: Determine whether the login data passed from the foreground matches the existing data in the database. // first, determine whether the user exists. If um is null, it indicates that the user does not exist // but is not null. The user may not exist because the data layer may return New usermodel (); // further judgment is required if (Um! = NULL) {// if the user exists, check whether the user ID and password match if (um. getuserid (). equals (LM. getuserid () & um. getpwd (). equals (LM. getpwd () {return true;} return false ;} /*** obtain user details by user ID * @ Param userid user ID * @ return corresponding user details */private usermodel finduserbyuserid (string userid) {// here, the specific processing is omitted. It only indicates that a usermodel um = new usermodel (); um object with default data is returned. setuserid (userid); um. setname ("test"); um. setpwd ("test"); um. setuuid ("user0001"); Return um ;}}
Staff
Package demo15.templatemethod. example2;/*** data model that describes the information entered during logon by a logon user */public class loginmodel {private string workerid, PWD; Public String getworkerid () {return workerid ;} public void setworkerid (string workerid) {This. workerid = workerid;} Public String getpwd () {return PWD;} public void setpwd (string PWD) {This. pwd = PWD ;}} **************************************** * ***************************** package demo1 5. templatemethod. example2;/*** logical processing of staff logon control */public class workerlogin {/*** determine whether the logon data is correct, that is, whether the logon is successful * @ Param lm encapsulate the model * @ return true of the logon data, indicating that the logon is successful. False indicates that the logon fails */Public Boolean login (loginmodel lm) {// 1: Obtain the employee data workermodel WM = this according to the employee ID. findworkerbyworkerid (LM. getworkerid (); // 2: Determine whether the user name passed from the front-end and the encrypted password data match the existing data in the database. // first, determine whether the staff exists, if WM is null, it indicates that the employee does not exist // but is not null, and the employee does not exist. // because the data layer may return the new worker Model (); therefore, further judgment is required if (WM! = NULL) {// 3: Use the corresponding encryption algorithm to encrypt the password data sent from the foreground. String encryptpwd = This. encryptpwd (LM. getpwd (); // if the employee exists, check whether the employee ID and Password Match if (WM. getworkerid (). equals (LM. getworkerid () & WM. getpwd (). equals (encryptpwd) {return true ;}} return false ;} /*** encrypt the password data * @ Param PWD the password data * @ return the encrypted password data */private string encryptpwd (string PWD) {// The password is encrypted here, and return PWD is omitted ;} /*** obtain detailed information of a staff member based on the staff ID * @ Param workerid staff ID * @ return details of the corresponding staff member */private workermodel findworkerbyworkerid (string workerid) {// The specific processing is omitted here, and only a diagram is provided. A workermodel WM = new workermodel (); WM object with default data is returned. setworkerid (workerid); WM. setname ("worker1"); WM. setpwd ("worker1"); WM. setuuid ("worker0001"); Return WM ;}} **************************************** * **************************** package demo15.templatemethod. example2;/*** data model describing staff information */public class workermodel {private string UUID, workerid, PWD, name; Public String getuuid () {return UUID ;} public void setuuid (string UUID) {This. UUID = UUID;} Public String getworkerid () {return workerid;} public void setworkerid (string workerid) {This. workerid = workerid;} Public String getpwd () {return PWD;} public void setpwd (string PWD) {This. pwd = PWD;} Public String getname () {return name;} public void setname (string name) {This. name = Name ;}}
2. What is the problem?

1. Too many repeated or similar code
2. it is inconvenient to scale up. If you change a function, you may need to change both features.
3. Use the template mode to Solve the Problem 3.1 Definition

Defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
3.2 structure and description of the template method

The template method is to abstract the same or similar, find the change and unchanged, then you can use the template method mode.
The structure is as follows:
 
3.3 sample code of template method mode

Package demo15.templatemethod. example3;/*** an abstract class that defines template methods and primitive operations */public abstract class abstractclass {/*** primitive operation 1. The so-called primitive operation is an abstract operation, must be implemented by the subclass */public abstract void doprimitiveoperation1 ();/*** primitive operation 2 */public abstract void doprimitiveoperation2 ();/*** template method, define the algorithm skeleton */public final void templatemethod () {doprimitiveoperation1 (); doprimitiveoperation2 ();}} **************************************** * ************************** package demo15.templatemethod. example3;/*** specific implementation class, implementing primitive operations */public class concreteclass extends abstractclass {public void doprimitiveoperation1 () {// specific implementation} public void doprimitiveoperation2 () {// specific implementation }}
4. Use the template method to override example 4.1loginmodel without changing. Below is a public logon control algorithm defined
Package demo15.templatemethod. example4;/*** logon control template */public abstract class logintemplate {/*** determine whether the logon data is correct, that is, whether the login is successful * @ Param lm encapsulate the login data model * @ return true indicates that the login is successful, and false indicates that the login fails */public final Boolean login (loginmodel lm) {// 1: loginmodel dblm = This. findloginuser (LM. getloginid (); If (dblm! = NULL) {// 2: encrypt the password string encryptpwd = This. encryptpwd (LM. getpwd (); // set the encrypted password to Lm in the login data model. setpwd (encryptpwd); // 3: determines whether the return this. match (LM, dblm);} return false ;} /*** search for and obtain the corresponding data in the storage according to the Login Number * @ Param loginid Login Number * @ return Login Number corresponding data in the storage */public abstract loginmodel findloginuser (string loginid ); /*** encrypt the password data * @ Param PWD password data * @ return the encrypted password data */Public String encryptpwd (string PWD) {return PWD ;} /*** determine whether the login data entered by the user matches the data in the storage * @ Param lm the login data entered by the user * @ Param dblm the data in the storage *@ return true indicates that the matching is successful, false indicates that the match fails */Public Boolean match (loginmodel LM, loginmodel dblm) {If (LM. getloginid (). equals (dblm. getloginid () & lm. getpwd (). equals (dblm. getpwd () {return true;} return false ;}}
4.2 normal users
Package demo15.templatemethod. example4;/*** common user logon logic processing */public class normallogin extends logintemplate {public loginmodel findloginuser (string loginid) {// The specific processing is omitted here, returns the loginmodel LM = new loginmodel (); lm. setloginid (loginid); lm. setpwd ("testpwd"); Return lm ;}}
4.3 Staff Login
Package demo15.templatemethod. example4;/*** staff logon logic processing */public class workerlogin extends logintemplate {public loginmodel findloginuser (string loginid) {// The specific processing is omitted here, returns the loginmodel LM = new loginmodel (); lm. setloginid (loginid); lm. setpwd ("workerpwd"); Return lm;} Public String encryptpwd (string PWD) {// override the method of the parent class to provide real encryption implementation // encrypt the password here, for example, MD5, 3DES, and so on are omitted. out. println ("using MD5 for password encryption"); Return PWD ;}}
4.4 client usage
Package demo15.templatemethod. example4; public class client {public static void main (string [] ARGs) {// prepare the information of the logon user loginmodel LM = new loginmodel (); lm. setloginid ("admin"); lm. setpwd ("workerpwd"); // The logintemplate () object used for judgment. Lt = new workerlogin (); logintemplate lt2 = new normallogin (); // perform the logon test Boolean flag = lt. login (LM); system. out. println ("can log on to the work platform =" + flag); Boolean flag2 = lt2.login (LM); system. out. println ("Common Logon Allowed =" + flag2 );}}
5. Mode explanation 5.1 key points

Function:Fixed the algorithm skeleton to make specific algorithms scalable.
Why not interface:An interface is a special abstract class. abstract classes do not necessarily contain abstract methods. abstract classes must have abstract methods.
When to use abstract classes:The Minutes constrain the behavior of sub-classes and provide public functions for sub-classes.
Hollywood rules:Don't contact us. We will contact you. The template as the parent class calls the corresponding method of the subclass as needed, that is, the parent class comes to the subclass, rather than the Child class to find the parent class.
The template method is a good embodiment of the open/closed principle and the Lee's replacement principle.
Java callback technology is a special template method mode.

5.2 nature

Fixed algorithm skeleton
5.3 advantages and disadvantages

Advantage: code reuse
Disadvantage: The algorithm skeleton is not easy to upgrade

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.