狀态模式很簡單,直接上代碼:
code:
/**
* 狀态接口
*/
interface State {
void execute();
}
/**
* 具體的三個狀态
*/
class StateA implements State{
@Override
public void execute() {
// TODO Auto-generated method stub
System.err.println("執行狀态A");
}
}
class StateB implements State{
@Override
public void execute() {
// TODO Auto-generated method stub
System.err.println("執行狀态B");
}
}
class StateC implements State{
@Override
public void execute() {
// TODO Auto-generated method stub
System.err.println("執行狀态C");
}
}
class Context{
private State state;
public Context(State state) {
super();
this.state = state;
}
public void contextInterface(){
state.execute();
}
}
public class Test {
public static void main(String[] args) {
new Context(new StateA()).contextInterface();
}
}
如果了解政策模式的同學可能會發現,怎麼和政策模式的實作如出一轍呢,對的,你的想法是正确的。
但是其實它們是有差別的,政策模式講的的是政策,在你的業務邏輯中一次隻能使用一種政策,狀态模式講的是狀态改變,
在每一個具體狀态角色中來指定後續狀态以及何時進行轉換。
實際中有這樣問題:
租戶在房屋租賃的時候一般有這幾個狀态:申請中,申請成功,申請失敗,退租中,退租成功,退租失敗
code:
/**
* 狀态接口
*/
interface State {
void execute(Person person) throws Exception;
}
/**
* 人定義
*/
class Person{
State state = null;
public State getState() {
return state;
}
public void setState(State state) {
try {
state.execute(this);//這裡使用了通路者模式
this.state = state;
System.err.println("設定成功");
} catch (Exception e) {
// TODO: handle exception
System.err.println("設定狀态異常");
}
}
}
/**
* 具體的六個狀态
*/
class SHQ_zhong implements State{//申請中
@Override
public void execute(Person person) throws Exception {
// TODO Auto-generated method stub
State s = person.getState();
if(s!=null){
throw new Exception();
}
}
}
class SHQ_is implements State{//申請成功
@Override
public void execute(Person person)throws Exception {
// TODO Auto-generated method stub
State s = person.getState();
if(!(s instanceof SHQ_zhong)){
throw new Exception();
}
}
}
class SHQ_no implements State{//申請失敗
@Override
public void execute(Person person) throws Exception{
// TODO Auto-generated method stub
State s = person.getState();
if(!(s instanceof SHQ_zhong)){
throw new Exception();
}
}
}
class TZ_zhong implements State{//退租申請中
@Override
public void execute(Person person)throws Exception {
// TODO Auto-generated method stub
State s = person.getState();
if(!(s instanceof SHQ_is)){
throw new Exception();
}
}
}
class TZ_is implements State{//退租成功
@Override
public void execute(Person person)throws Exception {
// TODO Auto-generated method stub
State s = person.getState();
if(!(s instanceof TZ_zhong)){
throw new Exception();
}
}
}
class TZ_no implements State{//退租失敗
@Override
public void execute(Person person) throws Exception{
// TODO Auto-generated method stub
State s = person.getState();
if(!(s instanceof TZ_zhong)){
throw new Exception();
}
}
}
public class Test {
public static void main(String[] args) {
Person p =new Person();
p.setState(new SHQ_zhong());
p.setState(new SHQ_is());
//p.setState(new TZ_zhong());
p.setState(new TZ_is());
}
}
總結:這裡也沒啥好總結,狀态模式和政策模式代碼結構可能完全一樣,但是他們也是有差别的。
狀态模式講究是狀态的改變,政策模式講究的是政策的選擇。PS:個人感覺政策模式和狀态模式的特例