定义

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

UML

设计模式——策略模式-LMLPHP

参考代码

#Character

package designmodel;

public abstract class Character {
    WeaponBehavior weaponBehavior;

    public void setWeaponBehavior(WeaponBehavior weaponBehavior) {
        this.weaponBehavior = weaponBehavior;
    }

    public void showWeapon() {
        weaponBehavior.useWeapon();
    }

    public abstract void fight();
}

#King

package designmodel;

public class King extends Character{
    public King() {
        this.weaponBehavior = new SwordBehavior();
    }

    @Override
    public void fight() {
        System.out.println("King fight");

    }
}

#Queen

package designmodel;

public class Queen extends Character{
    public Queen() {
        this.weaponBehavior = new KnifeBehavior();
    }
    @Override
    public void fight() {
        System.out.println("Queen fight");
    }
}

#Knight

package designmodel;

public class Knight extends Character{
    public Knight() {
        weaponBehavior = new BowAndArrowBehavior();
    }

    @Override
    public void fight() {
        System.out.println("Knigh fight");
    }
}

#WeaponBehavior

package designmodel;

public interface WeaponBehavior {
    public void useWeapon();
}

#AxeBehavior

package designmodel;

public class AxeBehavior implements WeaponBehavior{
    @Override
    public void useWeapon() {
        System.out.println("使用斧子砍劈");
    }
}

#BowANdArrowBehavior

package designmodel;

public class BowAndArrowBehavior implements WeaponBehavior{
    @Override
    public void useWeapon() {
        System.out.println("使用弓箭射击");
    }
}

#KnifeBehavior

package designmodel;

public class KnifeBehavior implements WeaponBehavior{
    @Override
    public void useWeapon() {
        System.out.println("使用匕首刺杀");
    }
}

#SwordBehavior

package designmodel;

public class SwordBehavior implements WeaponBehavior{
    @Override
    public void useWeapon() {
        System.out.println("使用宝剑挥舞");
    }
}

自测

package designmodel;

public class Main {
    public static void main(String[] args) {
        Character queue = new Queen();
        queue.showWeapon();
        queue.setWeaponBehavior(new AxeBehavior());
        queue.showWeapon();
    }
}

结果

使用匕首刺杀
使用斧子砍劈  

使用到的三个设计原则

找出应用中可能需要变化的部分,把它们独立出来,不要和不需要变化的代码混在一起(本利中使用武器不同,单独出来)
针对接口编程,而不是针对实现编程(绑的太死不容易修改)

多用组合,少用继承

06-29 22:15