- 策略模式
Charactor类
public abstract class Character {
UseWeaponBehavior weapon;
public void PerformWeapon() {
weapon.useWeapon();
}
public abstract void fight();
public void setWeapon(AxeBehavior weapon) {
this.weapon = weapon;
} }
Queen实现类
public class Queen extends Character {
@Override
public void fight() {
weapon=new SwordBehavior();
}
}
Troll实现类
public class Troll extends Character {
@Override
public void fight() {
weapon=new AxeBehavior();
}
}
King实现类
public class King extends Character {
public King(){
weapon=new KnifeBehavior();
}
@Override
public void fight() {
// weapon.useWeapon();
}
public void setWeapon(){
}
}
Knight类
public class Knight extends Character {
@Override
public void fight() {
weapon=new BowAndArrowBehavior();
}
}
行为类的实现接口
public interface UseWeaponBehavior {
public void useWeapon();
}
斧头类
public class AxeBehavior implements UseWeaponBehavior {
@Override
public void useWeapon() {
System.out.println("使用斧头武器刺杀");
}
}
弓箭类
public class BowAndArrowBehavior implements UseWeaponBehavior {
@Override
public void useWeapon() {
System.out.println("使用弓箭武器刺杀");
}
}
匕首类
public class KnifeBehavior implements UseWeaponBehavior {
@Override
public void useWeapon() {
System.out.println("使用匕首武器刺杀");
}
}
剑类
public class SwordBehavior implements UseWeaponBehavior {
@Override
public void useWeapon() {
System.out.println("使用剑武器刺杀");
}
}
Main函数类
public class Main{
public void main(String args[]){
Character character=new King();
character.PerformWeapon();
character.setWeapon(new AxeBehavior());
character.PerformWeapon();
}
}
注意几点
1.关注变化的部分,把变化的部分提升为行为类。
2.多用组合,少用继承。