java设计模式之策略模式

策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

情景模拟:

Character(角色)是抽象类,由具体的角色来继承。具体的角色包括:国王(King)、皇后(Queen)、骑士(Knight)、妖怪(Troll)。而Weapon(武器)是接口,由具体的武器来继承。所有实际的角色和武器都是具体类。

任何角色如果想换武器,还可以调用setWeapon()方法,此方法定义在Character超类中。在打斗(fight)过程中,会调用到目前武器的useWeapon()方法,攻击其它角色。

类图:
java设计模式之策略模式_第1张图片
Character类图
java设计模式之策略模式_第2张图片

Weapon类图
Character类代码实现:

package com.fight;

public abstract class Character {

WeaponBehavior weapon;
public abstract void fight();

public void setWeapon(WeaponBehavior w){
    this.weapon = w;
}

}

King类代码实现:

package com.fight;

public class King extends Character{

public King(){
    weapon = new SwordBehavior();
}

@Override
public void fight() {
    // TODO Auto-generated method stub
    weapon.useWeapon();
}

}

Queen类代码实现:

package com.fight;

public class Queen extends Character{

public Queen(){
    weapon = new KnifeBehavior();
}
@Override
public void fight() {
    // TODO Auto-generated method stub
    weapon.useWeapon();
}

}

Knight类代码实现:

package com.fight;

public class Knight extends Character{

public Knight(){
    weapon = new BowAndArrowBehavior();
}
@Override
public void fight() {
    // TODO Auto-generated method stub
    weapon.useWeapon();
}

}

Troll类代码实现:

package com.fight;

public class Troll extends Character{

public Troll(){
    weapon = new AxeBehavior();
}

@Override
public void fight() {
    // TODO Auto-generated method stub
    weapon.useWeapon();
}

}

WeaponBehavior类代码实现:

package com.fight;

public interface WeaponBehavior {

public void useWeapon();

}

SwordBehavior类代码实现:

package com.fight;

public class SwordBehavior implements WeaponBehavior{

//@Override
public void useWeapon() {
    // TODO Auto-generated method stub
    System.out.println("使用宝剑飞舞");
}

}

KnifeBehavior类代码实现:

package com.fight;

public class KnifeBehavior implements WeaponBehavior{

//@Override
public void useWeapon() {
    // TODO Auto-generated method stub
    System.out.println("使用匕首刺杀");
}

}

BowAndArrowBehavior类代码实现:

package com.fight;

public class BowAndArrowBehavior implements WeaponBehavior{

//@Override
public void useWeapon() {
    // TODO Auto-generated method stub
    System.out.println("使用弓箭射击");
}

}

AxeBehavior类代码实现:

package com.fight;

public class AxeBehavior implements WeaponBehavior {

//@Override
public void useWeapon() {
    // TODO Auto-generated method stub
    System.out.println("使用斧头砍劈");

}

}

测试类FightSimulator代码实现:

package com.fight;

public class FightSimulator {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Character character = new King();
    character.fight();
    character.setWeapon(new KnifeBehavior());
    character.fight();
}

}

运行结果:

使用宝剑飞舞
使用匕首刺杀

你可能感兴趣的:(java设计模式)