Java Policy mode

Source: Internet
Author: User

Defined:

is for the wrapper of the algorithm, separates the responsibility of using algorithm and the algorithm itself, delegating to different object management. The strategy pattern typically wraps a series of algorithms into a series of policy classes as subtypes of an abstract policy type. is: "Prepare a set of algorithms and encapsulate each algorithm so that they can be interchanged." ”

Intention:

For a set of algorithms, no algorithm is encapsulated in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client.



public class Straregydemo {public static void main (string[] args) {//TODO auto-generated method stubint[] Array = {5,66,8 8,21,58,99}; Bubblesort bsort = new Bubblesort (); Selectsort ssort = new Selectsort (); Context Con1 = new context (Bsort); Context Con2 = new context (ssort); Con1.sort (array); Con1.printarray (array); Con2.sort (array); Con2.printarray (array);}} Class Context{private Isort sort = null;public Context (isort sort) {this.sort = sort;} Instead of implementing the Sort method itself, call the Sort method public void sort (int[] array) {Sort.sort (array);} public void PrintArray (int[] array) {for (int i = 0;i<array.length;i++) {System.out.print (array[i]+ "");}}} Interface isort{void sort (int[] array);} Bubble Sort Method Class Bubblesort implements Isort{public void sort (int[] array) {System.out.println ("bubble Sort Method:"); for (int i = 0;i< array.length;i++) {for (int j = 0;j<array.length-i-1;j++) {if (array[j]>array[j+1]) {int temp = array[j];array[j] = a RRAY[J+1];ARRAY[J+1] = temp;}}} }}//Select Sort Method class Selectsort implements Isort{public void sort (iNt[] Array) {System.out.println ("Select Sort method:"); for (int i = 0;i<array.length;i++) {int min = i;for (int j = I+1;j<array.len gth;j++) {if (Array[min]>array[j]) {min = j;}} if (i!= min) {int temp = Array[i];array[i] = array[min];array[min] = temp;}}}

Java 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.