联零月 恋零月
关注数: 55 粉丝数: 518 发帖数: 44,365 关注贴吧数: 242
写状态模式的代码,为什么其中数据没办法继承? public class Player { //枚举所有的状态,currentState表示当前状态 private State state; private String name; private int lifeValue; public Player(String name,int lifeValue) { this.name = name; this.lifeValue = lifeValue; System.out.println(this.name + "游戏开始,初始血量为" + lifeValue); System.out.println("---------------------------------------------"); } public void setState(State state) { this.state = state; } //单击事件处理方法,封转了对状态类中业务方法的调用和状态的转换 public void pause() { state.pause(); } public void start() { state.start(); } public void beAttacked(int lifeValue) { state.beAttacked(lifeValue); } public void shot() { state.shot(); } public void move() { state.move(); } } //抽象状态类 abstract class State { protected Player player; protected int lifeValue; //public abstract void setState(Player player); public abstract void pause(); public abstract void start(); public abstract void beAttacked(int liveValue); public abstract void shot(); public abstract void move(); } //正常状态类 class NormalState extends State{ public NormalState(State state) { this.player = state.player; } public void pause() { player.setState(new PauseState(this)); } public void start() { //do nothing; } public void beAttacked(int life) { lifeValue-= life; System.out.println("您受伤了,目前血量为"+lifeValue); if(lifeValue<=0) { player.setState(new DeathState(this)); //转为阵亡状态 } } public void shot() { System.out.println("角色开始射击"); } public void move() { System.out.println("角色向前移动"); } } //二倍状态类 class PauseState extends State{ public PauseState(Player player,int lifeValue) { this.player = player; System.out.println("游戏暂停,您目前的血量为"+lifeValue); } public PauseState(State state) { this.player = state.player; } public void pause() { //do nothing; } public void start() { player.setState(new NormalState(this)); System.out.println("游戏开始"); } public void beAttacked(int lifeValue) { //do nothing; } public void shot() { //do nothing; } public void move() { //do nothing; } } //四倍状态类 class DeathState extends State{ public DeathState(State state) { this.player = state.player; } public void pause() { player.setState(new PauseState(this)); } public void start() { //do nothing; } public void beAttacked(int lifeValue) { System.out.println("血量已经归零"); } public void shot() { System.out.println("角色已经死亡,无法射击"); } public void move() { System.out.println("角色已经死亡,无法移动"); } } class Client { public static void main(String[] args) { Player player = new Player("Jack",100); player.setState(new PauseState(player,100)); player.start(); player.move(); player.shot(); player.beAttacked(10); player.beAttacked(10); player.beAttacked(10); player.pause(); } } 结果: 游戏开始 角色向前移动 角色开始射击 您受伤了,目前血量为-10 血量已经归零 血量已经归零 成功构建 (总时间: 0 秒) 不是血量设定成100吗?怎么转换一下状态就变成0了?
首页 1 2 3 4 下一页