研究State模式的人很多,网上有很多有价值的文章,尤其是那个遍历矩形的例子,相当好。看了很多,还是没太理解透彻,只好照葫芦画瓢了。
水的三种状态,冰(Ice) 液态水(LiquidWater)蒸汽(Steam)
加热(heatUp) 冷却(Cold)的时候改变状态。
package action.state2;
public interface Water {
public void handleHeat(Context c);
public void handleCold(Context c);
public void getUsage();
}
package action.state2;
public class Ice implements Water{
public void handleHeat(Context c) {
c.setWater(new LiquidWater());
}
public void handleCold(Context c) {
c.setWater(new Ice());
}
public void getUsage() {
System.out.println("We can skate now");
}
}
package action.state2;
public class LiquidWater implements Water{
public void handleHeat(Context c) {
c.setWater(new Steam());
}
public void handleCold(Context c) {
c.setWater(new Ice());
}
public void getUsage() {
System.out.println("It can be drink");
}
}
package action.state2;
public class Steam implements Water {
public void handleHeat(Context c) {
c.setWater(new Steam());
}
public void handleCold(Context c) {
c.setWater(new LiquidWater());
}
public void getUsage() {
System.out.println("It can warm bread now");
}
}
package action.state2;
public class Context {
private Water water = null;
public Water getWater() {
return water;
}
public void setWater(Water water) {
this.water = water;
}
public void HeatUp() {
water.handleHeat(this);
water.getUsage();
}
public void Cold() {
water.handleCold(this);
water.getUsage();
}
}
package action.state2;
public class Demo {
public static void main(String[] args) {
Water water=new Ice();
Context c=new Context();
c.setWater(water);
c.HeatUp();
c.HeatUp();
c.Cold();
c.Cold();
c.HeatUp();
}
}