引用一下某大的文章:
简单的说就是对某个对象的状态进行管理
举例,一个玩家释放某个技能会出现buff状态也可能出现debuff状态,那么我们使用一个manager来对buff和debuff进行相应的管理,这样的模式就是state模式。
1.Player.java
package com.xuyi.state;
public class Player {
private String buff;
private String debuff;
BuffManager buffManager = new BuffManager(this);
public void use_skill_1(){
buffManager.skill_1();
System.out.println("使用技能1----获得buff:"+buff+" 获得debuff:"+debuff);
}
public void use_skill_2(){
buffManager.skill_2();
System.out.println("使用技能2----获得buff:"+buff+" 获得debuff:"+debuff);
}
public String getBuff() {
return buff;
}
public void setBuff(String buff) {
this.buff = buff;
}
public String getDebuff() {
return debuff;
}
public void setDebuff(String debuff) {
this.debuff = debuff;
}
}
2.BuffManager.java
package com.xuyi.state;
public class BuffManager {
private static final String buff_state_1="回春术";
private static final String buff_state_2="魔法盾";
private static final String debuff_state_1="燃烧";
private static final String debuff_state_2="虚弱";
private Player player;
public BuffManager(Player player){
this.player=player;
}
public void skill_1(){
player.setBuff(buff_state_1);
player.setDebuff(debuff_state_1);
}
public void skill_2(){
player.setBuff(buff_state_2);
player.setDebuff(debuff_state_2);
}
}
3.Test.java
package com.xuyi.state;
//state模式-状态模式:简单的说就是对某个对象的状态进行管理
public class Test {
public static void main(String[] args) {
Player player = new Player();
player.use_skill_1();
player.use_skill_2();
}
}