---
title: "第七章 策略模式"
author: "crawler"
date: "2013-05-10T14:19:18Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-05-10T18:14:25Z"
id: 1866720
url: "https://crawler.iteye.com/blog/1866720"
---

**1.策略模式概述**

 

- 策略模式定义一系列算法，把它们一个个封装起来，并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
- 策略模式是处理算法的不同变体的一种成熟模式，策略模式通过接口或抽象类封装算法的标识，即在接口中定义一个抽象方法，实现该接口的类将实现接口中的抽象方法。

**2.策略模式-结构**

 

策略模式的结构中包括三种角色：  
 

- 策略（Strategy）
- 具体策略（ConcreteStrategy）
- 上下文（Context）

![](http://dl.iteye.com/upload/attachment/0084/2568/ccb2467f-c7d4-379d-8070-3e59e5c7f93d.jpg)  
 **3.策略模式-场景描述**

多个裁判给选手打分，然后根据不同的算法计算选手的最后得分  
策略一：求平均分  
策略二：利用几何平均值计算  
策略三：去掉最大值和最小值然后求平均分

**4.策略模式-场景分析**

 

- 抽象策略：Computable
- 具体策略：  
  StrategyOne  
  StrategyTwo  
  StrategyThree
- 上下文  
  GymnasticsGame

![](http://dl.iteye.com/upload/attachment/0084/2570/91fd252d-a54b-3687-a101-cee74562dc36.jpg)  
 **5.代码实现**

```
package patterns.strategy;

public interface Computable {
	public double computeScore(double scores[]);
}


package patterns.strategy;

public class StrategyOne implements Computable {

	public double computeScore(double[] scores) {
		double avg = 0;
		double sum = 0;
		if(scores!=null && scores.length!=0){
			for (double s:scores) {
				sum += s;
			}
			avg = sum/scores.length;
		}
		return avg;
	}

}


package patterns.strategy;

public class StrategyTwo implements Computable {

	public double computeScore(double[] scores) {
		double avg = 0;
		double sum = 1;
		if(scores!=null && scores.length!=0){
			for (double s:scores) {
				sum *= s;
			}
			avg = Math.pow(sum, 1.0/scores.length);
		}
		return avg;
	}

}



package patterns.strategy;

import java.util.Arrays;

public class StrategyThree implements Computable {

	public double computeScore(double[] scores) {
		double avg = 0;
		double sum = 0;
		if(scores!=null && scores.length>2){
			Arrays.sort(scores);
			for (int i=1;i<(scores.length-1);i++) {
				sum += scores[i];
			}
			avg = sum/(scores.length-2);
		}
		return avg;
	}

}


package patterns.strategy;

public class GymnasticsGame {
	private Computable comp = null;

	public void setComp(Computable comp) {
		this.comp = comp;
	}

	public double getPersonScore(double scores[]) {
		return comp.computeScore(scores);
	}

}


package patterns.strategy;

public class Client {
	public static void main(String[] args) {
		double scores[] = {92.21,93.23,98.91,97.32,99.02};
		GymnasticsGame game = new GymnasticsGame();
		game.setComp(new StrategyOne());
		double avg = game.getPersonScore(scores);
		System.out.println("第一种策略得分："+avg);
		
		game.setComp(new StrategyTwo());
		avg = game.getPersonScore(scores);
		System.out.println("第二种策略得分："+avg);
		
		game.setComp(new StrategyThree());
		avg = game.getPersonScore(scores);
		System.out.println("第三种策略得分："+avg);
	}
}
```

 **6.什么时候需要使用策略模式**

 

- 一个系统里面有许多类，他们之间的区别仅在于他们的行为，使用策略模式就是让使用其中行为中的一种
- 一个系统需要动态的提供几种算法，根据不同的选择可以选定某种算法参与到系统应用中，也就是将具体算法类设置成都有统一的接口，根据多态的特点可以生成同算法实现的子类
- 系统使用算法的数据不需要客户端知道，避免让客户端参与复杂的算法中去。
- 如果一个对象有很多种行为，不使用模式的话，会根据不同的选择写很多条件判断代码来实现，这样就违反了OCP原则，且不易维护