状态模式----pk------策略模式

时间:2022-08-13 22:01:33

最近学习设计模式,在看到状态模式和策略模式的时候,将其二者搞混,两者的UML图很像。

所以查找资料,翻阅文档  终于将二者分清。下面就聊聊二者的区别。

先来看状态模式的一个实例:

        做饭,有三种状态:      time<=10  未做熟

                                                  time<=20   熟了

                                                  time>20    烧糊了

        状态类接口:

public interface State {

public void boil(int time,make people);

}
/** * 为做熟的状态 * @author John * */public class UnderCooked implements State{@Overridepublic void boil(int time, make make) {// TODO Auto-generated method stub  if(time>10){  make.setState(new Cooked());  }else   System.out.println("烧烤"+time+"分钟,食物还未熟");}}

/**   食物熟了
* @author John
*
*/
public class Cooked implements State {


@Override
public void boil(int time, make make) {
// TODO Auto-generated method stub
if(time>20){
make.setState(new OverCook());
}else
System.out.println("烧烤"+time+"分钟,食物已经熟了,可以吃了");

}

}
/** * 食物烧糊了 * @author John * */public class OverCook implements State {@Overridepublic void boil(int time, make make) {// TODO Auto-generated method stub         System.out.println("烧烤"+time+"分钟,食物已经烧黑了,不能吃了");}}

状态模式----pk------策略模式



策略模式:

    两个数的运算

         

public interface Compute {
public int count(int a,int b);

}
加的算法

public class plus implements Compute {

@Override
public int count(int a,int b) {
// TODO Auto-generated method stub
return a+b;
}

}

乘的算法

public class multiply implements Compute {

@Override
public int count(int a, int b) {
// TODO Auto-generated method stub
return a*b;
}

}

辅助类

public class Context {
private Compute com;
public Context(){

}
public Context(Compute com){
this.com=com;
}
public void setCom(Compute com){
this.com=com;
}
int a=1;
int b=3;
public void count(){

System.out.println(com.count(a, b));

}

}

客户端

public class client {
public static void main(String args[]){
//相加
Context context=new Context();
context.setCom(new plus());


context.count();

//相乘

context.setCom(new multiply());
context.count();
}

}

从上面的代码及UML图可以看出两个模式结构大致相同

我感觉二者最大的区别就是:

      状态模式很好的定义了状态的转移次序,而策略模式则不需要,它可以在client端任意调用算法