策略模式,一般用来对某个功能根据不同的策略做不同的响应,实现过程很也简单。
将行为定义为策略接口,然后根据实际需要,我们去实现不同的具体策略。
然后通过在抽象类中持有策略行为的接口,子类在继承抽象类时,默认提供一种策略。
如果需要修改策略,只需要调用抽象类的设置策略方法即可。
举个栗子:
现在有一个教学行为策略的接口,TeachStrategy。
它有两个具体的实现:
- 教数学 MathTeachStrategy
- 教英语 EnglishTeachStrategy
一个教师抽象类Teacher
它有一个子类:
- 李老师 TeacherLi
策略模式怎么玩?
老师的抽象父类中持有一个教学策略引用,用户可以手动set新的策略。然后只要在老师的子类中定义一个默认的教学策略即可(通常在构造函数中实现一个默认的策略)。
更换策略的时候,只要set我们想要的就搞定了。
好了,上完整的代码:
public interface TeachStrategy {
//策略方法
public void teach();
}
public class EnglishTeachStrategy implements TeachStrategy {
//教英语
@Override
public void teach() {
System.out.println("teach english");
}
}
public class MathTeachStrategy implements TeachStrategy {
//教数学
@Override
public void teach() {
System.out.println("teach math");
}
}
public abstract class Teacher {
//持有教学策略引用
protected TeachStrategy teachStrategy;
public void setTeach(TeachStrategy teachStrategy) {
this.teachStrategy = teachStrategy;
}
//调用策略的具体实现
public void teach() {
if (teachStrategy != null) {
teachStrategy.teach();
}
}
}
public class TeacherLi extends Teacher {
//李老师默认教英语
public TeacherLi() {
teachStrategy = new EnglishTeachStrategy();
}
}
@Test
public void test() {
Teacher teacher = new TeacherLi();
//调用李老师的默认教学
teacher.teach();
//替换李老师的教学策略
teacher.setTeach(new MathTeachStrategy());
teacher.teach();
}