java策略设计模式,
分享于 点击 36347 次 点评:55
java策略设计模式,
一、策略模式的定义
1、定义了一组算法,将每个算法包装起来,并且使它们之间可以互换
2、策略模式使得在调用这些算法的时候能够不相互影响,改变不同算法的实现方式不影响其他算法的使用,即策略模式让算法独立于使用它们的客户端而独立变化。
二、策略模式体现了两个非常基本的面向对象设计的原则:
1、封装变化的概念。
2、编程中使用接口,而不是使用对接口的实现
三、策略模式的角色组成
抽象策略角色:策略类,通常是一个接口或者抽象类
具体策略角色:包装了相关的算法和行为,实现了策略类
环境角色:持有一个策略类的引用,最终给客户端调用的
四、编写策略模式的一般步骤
1、为策略对象定义一个公共接口
2、编写具体策略类,该类实现了上面的接口
3、在使用策略对象的类(即:环境角色)中保存一个对策略对象的引用
4、在使用策略对象的类中,实现对策略对象的set和get方法,或者使用构造方法完成赋值
5、客户端进行调用策略对象的引用
/*
不同算法对象的使用
*/
import java.util.Arrays;
public class Test{
public static void main(String[] args) {
ScoreManager manager = new ScoreManager();
manager.setArithmetic(new ErFenLookup());
manager.max();
}
}
interface LookupArithmetic{
float loopup(float[] scores);
}
class ShunXuLookup implements LookupArithmetic{
public float loopup(float[] scores){
System.out.println("顺序查找算法");
return 0;
}
}
class ErFenLookup implements LookupArithmetic{
public float loopup(float[] scores){
System.out.println("二分查找算法");
return 0;
}
}
class FenKuaiLookup implements LookupArithmetic{
public float loopup(float[] scores){
System.out.println("分块查找算法");
return 0;
}
}
class HashLookup implements LookupArithmetic{
public float loopup(float[] scores){
System.out.println("哈希查找算法");
return 0;
}
}
class ScoreManager{
protected float[] scores = new float[3];
protected int count = 0;
protected LookupArithmetic arithmetic;
public void setArithmetic(LookupArithmetic arithmetic){
this.arithmetic = arithmetic;
}
//添加
public void add(float item){
if (count == scores.length) {
int newLength = 2 * scores.length;
scores = Arrays.copyOf(scores, newLength);
}
scores[count] = item;
count++;
}
//查找最大值
public float max(){
return arithmetic.loopup(scores);
}
}
相关文章
- 暂无相关文章
用户点评