策略模式
1.概念
定义算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
2.体现的设计原则
(1)封装变化:找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起。
(2)多用组合,少用继承。
(3)针对接口编程,不针对实现编程。
3.实现示例
武器接口:
package behavior;
public interface WeaponBehavior {
public void useWeapon();
}
武器实现类:
package behavior;
public class AxeBehavior implements WeaponBehavior {
@Override
public void useWeapon() {
System.out.println("use axe");
}
}
package behavior;
public class KnifeBehavior implements WeaponBehavior {
@Override
public void useWeapon() {
System.out.println("use knife");
}
}
package behavior;
public class SwordBehavior implements WeaponBehavior{
@Override
public void useWeapon() {
System.out.println("use sword");
}
}
抽象类:
package characterTest;
import behavior.WeaponBehavior;
public abstract class Character {
WeaponBehavior weapon;
public abstract void display();
//传入不同的实现类,就可以实现不同的形为
public void setWeapon(WeaponBehavior w) {
this.weapon = w;
}
public void fight(){
weapon.useWeapon();
}
}
具体的实现类:
package characterTest;
import behavior.SwordBehavior;
public class King extends Character {
public King(){
weapon = new SwordBehavior();
}
@Override
public void display() {
System.out.println("I'm king");
}
}
package characterTest;
import behavior.KnifeBehavior;
public class knight extends Character {
public knight(){
weapon = new KnifeBehavior();
}
@Override
public void display() {
System.out.println("I'm a knight");
}
}
package characterTest;
import behavior.AxeBehavior;
public class Queen extends Character {
public Queen(){
weapon = new AxeBehavior();
}
@Override
public void display() {
System.out.println("I'm a queen");
}
}
测试函数:
package characterTest;
import behavior.AxeBehavior;
import behavior.KnifeBehavior;
import behavior.SwordBehavior;
public class CharacterTest {
public static void main(String[] args) {
Character king = new King();
king.setWeapon(new SwordBehavior());
king.fight();
king.display();
Character queen = new Queen();
queen.setWeapon(new AxeBehavior());
queen.fight();
Character knight = new Queen();
knight.setWeapon(new KnifeBehavior());
knight.fight();
}
}