策略模式
package lloo; public class Application1 { public static void main (String args[]) { Character character=new Character(); character.setWeaponBehavior(new KnifeBehavior()); character.setName("king"); int n=200; //武器伤害值 character.display(n); System.out.printf("%s的武器装备:%4d\n",character.getName(),character.fight()); System.out.println("匕首刺杀"); character.setWeaponBehavior(new SwordBehavior()); character.setName("Queen"); int n1=400; //武器伤害值 character.display(n1); System.out.printf("%s的武器装备:%4d\n",character.getName(),character.fight()); System.out.println("长剑刺杀"); character.setWeaponBehavior(new AxeBehavior()); character.setName("Knight"); int n2=300;//武器伤害值 character.display(n2); System.out.printf("%s的武器装备:%4d\n",character.getName(),character.fight()); System.out.println("斧头劈砍"); character.setWeaponBehavior(new BowAndArrowBehavior()); character.setName("Troll"); int n3=100; //武器伤害值 character.display(n3); System.out.printf("%s的武器装备:%4d\n",character.getName(),character.fight()); System.out.println("弹弓射击"); } }
package lloo; public class AxeBehavior implements WeaponBehavior { public void useWeapon(int n) {
}
}
package lloo; public class BowAndArrowBehavior implements WeaponBehavior { public void useWeapon(int n) { } }
package lloo; public class Character { WeaponBehavior weaponBehavior; String name; int f; public void setWeaponBehavior(WeaponBehavior weaponBehavior) { this.weaponBehavior=weaponBehavior; } public void display(int n) { f=n; if (weaponBehavior!=null) weaponBehavior.useWeapon(n); else System.out.println("没有武器可用"); } public int fight( ) { return f; } public void setName(String s) { name=s; } public String getName() { return name; } }
package lloo; public class KnifeBehavior implements WeaponBehavior { public void useWeapon(int n) { } }
package lloo; public class SwordBehavior implements WeaponBehavior { public void useWeapon(int n) { } }
package lloo; public interface WeaponBehavior { public void useWeapon(int n); }