[Java design mode] policy Mode

Source: Internet
Author: User

1. Background Knowledge

Policy mode, as a software design mode, indicates that an object has a certain behavior, but in different scenarios, this behavior has different implementation algorithms. For example, everyone needs to "pay personal income tax", but "pay personal income tax in the United States" and "pay personal income tax in China" have different tax calculation methods. The policy mode encapsulates different algorithms and calls different objects to use different algorithms based on client requirements, saving a lot of code like if-else.

2. This example consists of three algorithms: algorithm 1: multiply the number by 1, algorithm 2 by 2, and algorithm 3 by 3. The client calls the second algorithm. Calculate. java-interfaces of the three algorithms
Public interface Calculate {/** algorithm interface, returns the specific algorithm */public int calnumber (int number );}

FirstCalculate. java-first algorithm, the remaining two algorithms are omitted
Public class FirstCalculate implements Calculate {@ Overridepublic int calnumber (int number) {// TODO Auto-generated method stubSystem. out. println (algorithm 1); return number ;}}

Context. java-set the algorithm Environment
Public class Context {Calculate cal;/** constructor, set the algorithm object used */public Context (Calculate cal) {this. cal = cal;}/** pass data to the corresponding algorithm */public int SetNumber (int number) {return cal. calnumber (number );}}

Client. java-entry function
public class Client {public static void main(String[] args) {         Calculate cal=new SecondCalculate();Context con=new Context(cal);int result=con.SetNumber(300);System.out.println(result);    }  }

Result
3. Example source code

Click to download source code

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.