设计模式(二)---策略模式

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

/**
* 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();
}
}



posted on 2017-11-10 15:26  在窗边的豆豆助  阅读(120)  评论(0编辑  收藏  举报