概述
策略模式算是设计模式中比较好理解的,其实就是在运行期间动态的修改一个抽象类的具体实现,从而实现了每个具体类的不同的"策略"。
组成
—抽象策略角色: 策略类,通常由一个接口或者抽象类实现。
—具体策略角色:包装了相关的算法和行为。
—环境角色:持有一个策略类的引用,最终给客户端调用。
代码实现
//抽象策略角色
public interface Strategy{
void attendClass();//上课
}
//具体策略角色
public class ChineseTeacher implements Strategy{
private String name;
public ChineseTeacher(String name){
this.name=name;
}
@Override
public void attendClass(){
System.out.println(name + " 来上课了!");
}
}
public class EnglishTeacher implements Strategy{
private String name;
public EnglishTeacher(String name){
this.name=name;
}
@Override
public void attendClass(){
System.out.println(name + " 来上课了!");
}
}
public class MathTeacher implements Strategy{
private String name;
public MathTeacher(String name){
this.name=name;
}
@Override
public void attendClass(){
System.out.println(name + " 来上课了!");
}
}
//环境角色
public class Context{
private Strategy strategy;
public Context(){}
public void setContext(Strategy strategy){
this.strategy=strategy;
}
public void contextInterface(){
if(strategy==null){
System.out.println("请选择老师");
return;
}
strategy.attendClass();
}
}
//测试类
public class Test{
public static void main(String[] args){
Context context=new Context();
ChineseTeacher chineseTeacher=new ChineseTeacher("语文老师");
EnglishTeacher englishTeacher=new EnglishTeacher("英语老师");
MathTeacher mathTeacher=new MathTeacher("数学老师");
context.setContext(chineseTeacher);
context.contextInterface();
context.setContext(englishTeacher);
context.contextInterface();
context.setContext(mathTeacher);
context.contextInterface();
}
}