设计模式笔记——策略模式

设计原则

  1. 找出应用中可能会变化的部分,把它们独立出来,不要和那些不需要变化的代码混在一起。
  2. 针对接口编程,而不是针对实现编程。
  3. 多用组合,少用继承。

策略模式

定义了算法族(一组行为),分别封装起来,让他们之间可以相互替换。该模式让算法的变化独立于使用算法的用户。
应用示例:一个动作冒险游戏,有多个游戏角色和多种游戏武器,角色可以切换武器。

角色实现

// 抽象角色
public abstract class Role {
    public abstract void fight(); //抽象行为,战斗
}
// 国王角色
pubblic class King extends Role {
    public King() {
        name = "king";
    }

    @Override
    public void fight() {
        if (weaponBehavior == null) {
            System.out.println(name + ": no weapon! With fist!");
        } else {
            System.out.print(name + ": ");
            weaponBehavior.useWeapon();
        }
    }
}
// 王后角色
public class Queen extends Role {
    public Queen() {
        name = "queen";
    }

    @Override
    public void fight() {
        if (weaponBehavior == null) {
            System.out.println(name + ": no weapon! With fist!");
        } else {
            System.out.print(name + ": ");
            weaponBehavior.useWeapon();
        }
    }
}

行为(算法族)实现

// 抽象武器行为
public interface WeaponBehavior {
    void useWeapon();
}
// 使用枪
public class Gun implements WeaponBehavior {
    @Override
    public void useWeapon() {
        System.out.println("use gun to shoot.");
    }
}
// 使用匕首
public class Knife implements WeaponBehavior {
    @Override
    public void useWeapon() {
        System.out.println("use knife to stab.");
    }
}

测试类

//测试类
public class Test {
    public static void main(String[] args) {
        // 国王角色
        Role roleKing = new King();
        roleKing.fight();
        roleKing.setWeapon(new Knife());
        roleKing.fight();
        roleKing.setWeapon(new Gun());
        roleKing.fight();
        // 王后角色
        Role roleQueen = new Queen();
        roleQueen.fight();
        roleQueen.setWeapon(new Gun());
        roleQueen.fight();
        roleQueen.setWeapon(new Knife());
        roleQueen.fight();
    }
}

测试输出:

king: no weapon! With fist!
king: use knife to stab.
king: use gun to shoot.
queen: no weapon! With fist!
queen: use gun to shoot.
queen: use knife to stab.
发布了26 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/China_Style/article/details/78797936
今日推荐