Java Learning notes-design pattern 15 (Template method mode)

Source: Internet
Author: User

Intention

Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

Refers to: An abstract class, there is a main method, and then define 1...N methods, can be abstract, can also be the actual method, define a class, inherit the abstract class, override the abstract method, by invoking the abstract class, implement the Call of the child class

Public abstract class Abstractcalculator {            /* Main method, which implements calls to other methods of this class *      /public final int calculate (String exp,string opt) {          int array[] = split (exp,opt);          Return calculate (array[0],array[1]);      }            /* Method overridden by the quilt class *      /abstract public int calculate (int num1,int num2);            Public int[] Split (string exp,string opt) {          string array[] = Exp.split (opt);          int arrayint[] = new int[2];          Arrayint[0] = Integer.parseint (array[0]);          ARRAYINT[1] = Integer.parseint (array[1]);          return arrayint;      }  }  

  

public class Plus extends Abstractcalculator {        @Override public      int calculate (int num1,int num2) {          return num 1 + num2;      }  }

Test

public class Strategytest {public        static void Main (string[] args) {          String exp = "8+8";          Abstractcalculator cal = new Plus ();          int result = Cal.calculate (exp, "\\+");          SYSTEM.OUT.PRINTLN (result);      }  }

  

Transferred from: http://blog.csdn.net/zhangerqing/article/details/8243942

Java Learning notes-design pattern 15 (Template method mode)

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.