策略模式:它定义了算法家族,分别封装起来,让他们之间可以相互替代,此模式让算法发生变化,不会影响到使用算法的客户。
我们继续来打去学校的例子。先看代码。
定义一个策略接口:
public interface ToSchoolStrategy {
public void toSchool();
}
策略实现:
public class ExceptionalStrategy implements ToSchoolStrategy {
@Override
public void toSchool() {
System.out.println("父母送");
}
}
public class GenerallyStrategy implements ToSchoolStrategy {
@Override
public void toSchool() {
System.out.println("坐校车");
}
}
定义一个学生。
public class Student {
public void toSchool(ToSchoolStrategy to){
to.toSchool();
}
public void goHome(ToSchoolStrategy to){
to.toSchool();
}
}
client
public static void main(String[] args) {
ToSchoolStrategy to = new GenerallyStrategy();
ToSchoolStrategy to1 = new ExceptionalStrategy();
Student studentA = new Student();
System.out.println("A同学");
studentA.toSchool(to);
studentA.goHome(to1);
Student studentB = new Student();
System.out.println("B同学");
studentB.toSchool(to);
studentB.goHome(to);
}
那么学生想去学校想回家就可以调用不同的策略来实现他的去学校功能。去学校的策略就是我们封装起来的算法
,我们无论怎么替换去学校的策略。都不会影响我们同学学习。简单来说就是这样子。
我们这么看其实挺好理解的,但是当你看到状态模式的时候你就会怀疑这两者有差别么?
我们先看一下状态模式的代码把。我们可以保留策略模式的两种去学校策略只改变我们的学生类。
public class Student {
private ToSchoolStrategy to = new GenerallyStudent();
public void setHealthIndex(int healthIndex){
if(healthIndex>50)
to = new GenerallyStudent();
else
to = new Exceptionalstudent();
}
public void toSchool(){
to.toSchool();
}
public void goHome(){
to.toSchool();
}
}
client
public static void main(String[] args) {
Student studentA = new Student();
studentA.toSchool();
studentA.setHealthIndex(45);//腿部受伤
studentA.goHome();
}
是不是感觉这两不就是一个东西么?
状态模式:当一个对象的内在 状态改变时,允许改变其行为,这个对象像是改变了其类。
但是策略模式是围绕可以互换的算法来创建成功业务的,然而状态模式是通过改变对象内部的状态来帮助对象控制自己行为的。前者行为是彼此独立、可以相互替换的,后者行为是不可以相互替换的。
也就是说腿部首相身体健康指标下降。然后必须家长来接,而策略模式主要表达去学校的两种形式,无论用那种都可以达到去学校回家的目的。而状态模式是某种状态需要怎么去学校,当你腿部受伤时,你必须让你们接,因此是不可替代的。