-- 决策者模式 即具体的策略方法(实体)选择由客户端决定
一、模式结构
组成(角色) | 关系 | 作用 |
---|---|---|
策略抽象类(Builder) | 具体策略的抽象类 | 提供具体策略成员 |
具体策略(Concrete Builder) | 策略实例 | 实现不同的策略 |
指导者Context(Director) | 具体策略与客户端中间件 | 调用具体策略的方法功能 |
二、决策者模式优缺点
1、优点
- 策略类的等级结构定义了一个策略或行为族,公共的代码可以写在抽象类里,从而避免重复
- 可以选择反射让客户端选择决策哪一种策略实现,从而动态改变策略
2、缺点
- 客户端需知道哪种策略之间的区别和名称的对应
- 策略类的过多,这里可以用享元模式(结构模式)来减少对象的数量
三、栗子
1、策略抽象类 - 算法策略集
package com.construction.strategy;
public interface Arithmetic {
//算法处理抽象方法
double deal(double num);
}
2、具体策略
(1)、算法1
package com.construction.strategy;
/**
* @description: 算法1
* @author: ziHeng
* @create: 2018-08-06 17:24
**/
public class Arithmetic1 implements Arithmetic{
@Override
public double deal(double num) {
return num=num*0.8;
}
}
(2)、算法2
package com.construction.strategy;
/**
* @description: 算法1
* @author: ziHeng
* @create: 2018-08-06 17:24
**/
public class Arithmetic2 implements Arithmetic{
@Override
public double deal(double num) {
return num=num*0.5;
}
}
3、指导者 - Context
package com.construction.strategy;
/**
* @description:
* @author: ziHeng
* @create: 2018-08-06 17:32
**/
public class Context{
private Arithmetic arithmetic;
//构造方法注入策略类
public Context(Arithmetic arithmetic) {
this.arithmetic = arithmetic;
}
public double calculate(double num) {
//交给策略类处理
return arithmetic.deal(num);
}
}
调用Test类:
package com.construction.strategy;
/**
* @description: 策略模式测试
* @author: ziHeng
* @create: 2018-08-06 17:28
**/
public class StrategyTest {
public static void main(String[] args) {
double num = 100;
Context context = new Context(new Arithmetic2());
double calculate = context.calculate(num);
System.out.println(calculate);
}
}