状态设计模式:允许一个对象改变它的行为当它的内部状态改变时。这个对象看起来好像 改变了类型。
示例代码:
class Actor {
public void act() {
}
}
class HappyActor extends Actor {
public void act() {
System.out.println("Happy act");
}
}
class SadActor extends Actor {
public void act() {
System.out.println("Sad act");
}
}
class Stage {
private Actor actor = new HappyActor();
public void change() {
actor = new SadActor();
}
public void act() {
actor.act();
}
}
public class Transmogrify {
public static void main(String[] args) {
Stage stage = new Stage();
stage.act();
stage.change();
stage.act();
}
}
---------------------------------------------------------------
interface Light {
public void light();
public void change(Road road);
}
class GreenLight implements Light {
public void light() {
System.out.println("Green: please pass");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void change(Road road) {
road.change(new YellowLight());
}
}
class YellowLight implements Light {
public void light() {
System.out.println("Yellow: please take care");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void change(Road road) {
road.change(new RedLight());
}
}
class RedLight implements Light{
public void light() {
System.out.println("Red: please stop");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void change(Road road) {
road.change(new GreenLight());
}
}
class Road {
private Light signLight;
public Road() {
signLight = new RedLight();
}
public void change(Light signLight) {
this.signLight = signLight;
}
public void run() {
while (true) {
signLight.light();
signLight.change(this);
}
}
}
public class Demo {
public static void main(String[] args) {
Road road = new Road();
road.run();
}
}