Java Learning notes-design pattern 14 (policy mode)

Source: Internet
Author: User

Intention

Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be independent of the customers who use it.

The strategy mode is used in the algorithm decision-making system, the external user only needs to decide which algorithm to use.

Public interface ICalculator {public      int calculate (String exp);  }  
Public abstract class Abstractcalculator {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 implements ICalculator {        @Override public      int Calculate (String EXP) {          int arrayint[] = Split (exp, "\\+");          return arrayint[0]+arrayint[1];      }  
public class minus extends Abstractcalculator implements ICalculator {        @Override public      int calculate (String exp ) {          int arrayint[] = Split (exp, "-");          return arrayint[0]-arrayint[1];      }    }  

Test

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

 

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

Java Learning notes-design pattern 14 (policy 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.