状态模式很简单,直接上代码:
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:个人感觉策略模式和状态模式的特例