最近學習設計模式,在看到狀態模式和策略模式的時候,將其二者搞混,兩者的UML圖很像。
所以查找資料,翻閱文檔 終於將二者分清。下面就聊聊二者的區別。
先來看狀態模式的一個實例:
做飯,有三種狀態: time<=10 未做熟
time<=20 熟了
time>20 燒糊了
狀態類接口:
public interface State {
public void boil(int time,make people);
}
/**
* 爲做熟的狀態
* @author John
*
*/
public class UnderCooked implements State{
@Override
public 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 {
@Override
public void boil(int time, make make) {
// TODO Auto-generated method stub
System.out.println("燒烤"+time+"分鐘,食物已經燒黑了,不能吃了");
}
}
策略模式:
兩個數的運算
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端任意調用算法