码迷,mamicode.com
首页 > 编程语言 > 详细

java策略模式

时间:2018-02-14 15:35:08      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:子类   div   nbsp   gpo   void   highlight   sso   class   rate   

定义:

  是对于算法的包装,把使用算法的责任和算法本身分隔,委派给不同的对象管理。策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类型的子类型。就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换。”

 

意图:

  针对一组算法,将没哟个算法封装到具有共同接口的独立类中,从而使得它们可以互相替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。



public class StraregyDemo { public static void main(String[] args) { // TODO Auto-generated method stub int[] 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策略模式

标签:子类   div   nbsp   gpo   void   highlight   sso   class   rate   

原文地址:https://www.cnblogs.com/liubing2018/p/8448351.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!