Java设计模式之设计模式
策略模式:策略模式定义了算法簇,分别封装起来,让他们之间可以互相替换,此设计模式让算法的变化独立于使用算法的客户.
一个简单的代码实现:
public abstract class Character {
WeaponBehaveior weapon;
abstract void fight();
public void show(){
weapon.useWeapon();
}
public void setWeapon(WeaponBehaveior wb){
weapon=wb;
}
}
声明一个父类
public interface WeaponBehaveior {
void useWeapon();
}
声明接口
public class KnifeBehavior implements WeaponBehaveior {
public void useWeapon() {
System.out.println("use Kinfe fight");
}
}
public class AxeBehavior implements WeaponBehaveior {
@Override
public void useWeapon() {
System.out.println("use Axe fight");
}
}
接口的实现类
public class King extends Character {
private String name;
public King(String name){
this.name=name;
weapon=null;
}
@Override
void fight() {
System.out.println("I'm fight");
}
}
父类的子类,继承父类的weapon
public class DesignMode {
public static void main(String[] args) {
Character ch=new King("Tom");
ch.setWeapon(new KnifeBehavior());
ch.fight();
ch.show();
}
}