Strategy
Weapon
public abstract class Weapon {
//打斗
public abstract void fight();
}
NoneWeapon
public class NoneWeapon extends Weapon{
@Override
public void fight() {
System.out.println("空手...");
}
}
Policeman
public class Policeman {
private Weapon weapon;
public Policeman(Weapon initialWeapon) {
this.weapon = initialWeapon;
}
public void changeWeapon(Weapon newWeapon) {
this.weapon = newWeapon;
}
public void useWeapon(){
this.weapon.fight();
}
}
Hostage
public class Hostage extends NoneWeapon{
private Weapon weapon;
public Hostage() {
}
public Hostage(Weapon initialWeapon) {
this.weapon = initialWeapon;
}
public void changeWeapon(Weapon newWeapon) {
this.weapon = newWeapon;
}
public void useWeapon(){
weapon.fight();
}
}
Dagger
public class Dagger extends Weapon{
@Override
public void fight() {
System.out.println("挥舞匕首...");
}
}
Grenade
public class Grenade extends Weapon{
@Override
public void fight() {
System.out.println("抛出手雷...");
}
}
Machincgun
public class Machincgun extends Weapon{
@Override
public void fight() {
System.out.println("机关枪扫射...");
}
}
Main
public class Main {
public static void main(String[] args) {
Weapon machincgun = new Machincgun();
Weapon grenade = new Grenade();
Weapon dagger = new Dagger();
Policeman peter = new Policeman(dagger);
Hostage mary = new Hostage();
mary.useWeapon();
while (true) {
String s = new Scanner(System.in).next();
char c = s.charAt(0);
switch (c) {
case '1': peter.changeWeapon(machincgun);break;
case '4': peter.changeWeapon(grenade);break;
case '3': peter.changeWeapon(dagger);break;
}
peter.useWeapon();
}
}
}