java策略模式

來源:互聯網
上載者:User

標籤:子類   div   nbsp   gpo   void   highlight   sso   class   rate   

定義:

  是對於演算法的封裝,把使用演算法的責任和演算法本身分隔,委派給不同的對象管理。策略模式通常把一個系列的演算法封裝到一系列的策略類裡面,作為一個抽象策略類型的子類型。就是:“準備一組演算法,並將每一個演算法封裝起來,使得它們可以互換。”

 

意圖:

  針對一組演算法,將沒喲個演算法封裝到具有共同介面的獨立類中,從而使得它們可以互相替換。策略模式使得演算法可以在不影響到用戶端的情況下發生變化。



public class StraregyDemo {public static void main(String[] args) {// TODO Auto-generated method stubint[] array = {5,66,88,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;}//本身沒有實現排序方法,而是調用排序方法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);}//冒泡排序法class BubbleSort implements iSort{public void sort(int[] array) {System.out.println("冒泡排序法:");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] = array[j+1];array[j+1] = temp;}}} }}//選擇排序法class SelectSort implements iSort{public void sort(int[] array) {System.out.println("選擇排序法:");for(int i = 0;i<array.length;i++) {int min = i;for(int j = i+1;j<array.length;j++) {if(array[min]>array[j]) {min = j;}}if(i!= min) {int temp = array[i];array[i] = array[min];array[min] = temp;}}}}

 

java策略模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.