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

/**
* Created by wqc on 2017/10/3.
* 算法抽象类(武器抽象类)
*/
public interface WeaponBehavior {
public void useWeapon();
}

/**
* Created by wqc on 2017/10/3.
* 具体算法策略:斧头(使用的武器)
*/
public class AxeBehavior implements WeaponBehavior {

@Override
public void useWeapon() {
System.out.println("use axe .........");
}
}

/**
* Created by wqc on 2017/10/3.
* 具体算法策略:剑(使用的武器)
*/
public class SwordBehavior implements WeaponBehavior {
@Override
public void useWeapon() {
System.out.println("use sword............");
}
}

/**
* Created by wqc on 2017/10/3.
* 使用算法策略的用户(这里指使用工具的人)抽象类
*/
public abstract class Charactor {
WeaponBehavior weapon;

public void fight() {

}

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

}

/**
* Created by wqc on 2017/10/3.
* 使用算法策略的用户(这里指使用工具的人)具体实现类
*
*/
public class King extends Charactor {
public void fight() {
System.out.println("King fight......");
weapon.useWeapon();
}
}
/**
* Created by wqc on 2017/10/3.
* 策略模式:定义了算法族,分别分装起来,让它们之间可以相互替换,此模式让算法的变化可以独立于使用算法的用户。
*/
public class test {
public static void main(String[] args) {
Charactor king = new King();
WeaponBehavior sw = new SwordBehavior();
king.setWeapon(sw);
king.fight();

WeaponBehavior axe = new AxeBehavior();
king.setWeapon(axe);
king.fight();
}
}



相关文章:

  • 2021-12-17
  • 2021-07-12
  • 2021-08-08
  • 2022-12-23
  • 2021-05-20
  • 2021-08-06
  • 2021-06-30
  • 2022-01-15
猜你喜欢
  • 2018-06-22
  • 2018-07-23
  • 2021-06-12
  • 2022-01-12
  • 2018-09-29
  • 2021-12-15
  • 2021-06-09
相关资源
相似解决方案