Java設(shè)計(jì)模式之設(shè)計(jì)模式
策略模式:策略模式定義了算法簇,分別封裝起來,讓他們之間可以互相替換,此設(shè)計(jì)模式讓算法的變化獨(dú)立于使用算法的客戶.
一個(gè)簡單的代碼實(shí)現(xiàn):
public abstract class Character {
WeaponBehaveior weapon;
abstract void fight();
public void show(){
weapon.useWeapon();
}
public void setWeapon(WeaponBehaveior wb){
weapon=wb;
}
}
聲明一個(gè)父類
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");
}
}
接口的實(shí)現(xiàn)類
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();
}
}