标签:
状态模式,又称状态对象模式(Pattern of Objects for States),状态模式是对象的行为模式。状态模式允许一个对象在其内部状态改变的时候改变其行为。这个对象看上去就像是改变了它的类一样。
public class Person { private PersonState state; public Person(PersonState state) { this.state = state; } public void changeState(PersonState state) { this.state = state; } public void smile() { if(state == PersonState.HAPPY) { System.out.println("哈哈大笑"); } else if(state == PersonState.UNHAPPY) { System.out.println("苦笑"); } } public void cry() { if(state == PersonState.HAPPY) { System.out.println("喜极而泣"); } else if(state == PersonState.UNHAPPY) { System.out.println("痛哭流泪"); } } } enum PersonState { HAPPY, UNHAPPY }
测试
public static void main(String[] args) { Person p = new Person(PersonState.HAPPY); p.smile(); p.cry(); p.changeState(PersonState.UNHAPPY); p.smile(); p.cry(); }
OK,问题是解决了,Person可以在高兴和不高兴时笑和哭表现出不同的状态,问题来了,一个人并不是只有高兴和不高兴两种状态,比如正常情况下人也会笑(微笑)也会哭(感动的哭),此时要对这种状态做出响应,只能修改Person类的代码了!
抽象出Person的状态
public interface PersonState { void smile(); void cry(); }
高兴时的哭、笑
public class PersonHappyState implements PersonState { @Override public void smile() { System.out.println("哈哈大笑"); } @Override public void cry() { System.out.println("喜极而泣"); } }
不高兴时的哭、笑
public class PersonUnhappySate implements PersonState { @Override public void smile() { System.out.println("苦笑"); } @Override public void cry() { System.out.println("痛哭流泪"); } }
Person
public class Person { private PersonState state; public Person(PersonState state) { this.state = state; } public void changeState(PersonState state) { this.state = state; } public void smile() { state.smile(); } public void cry() { state.cry(); } }
测试
public class Test { public static void main(String[] args) { PersonState happy = new PersonHappyState(); Person p = new Person(happy); p.smile(); p.cry(); PersonState unhappy = new PersonUnhappyState(); p.changeState(unhappy); p.smile(); p.cry(); } }
OK,这时再添加正常状态时哭、笑就很简单了,只需实现PersonState接口,实现自己的smile和cry方法。
标签:
原文地址:http://www.cnblogs.com/wangj1130/p/4822945.html