设计模式--策略模式

示例:

Character是角色类,是抽象类,由具体的角色来继承,Weapon是武器接口,有具体的武器来实现。任何角色想换武器可以有setWeapon方法来实现,在角色fight过程中使用武器的useWeapon方法,进行攻击。

UML:

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

将WeaponBehavior封装成接口,接口的实现可以相互替换。

原则:

  • 封装变化       

  把系统中会变化的部分抽取出来进行封装。此处将WeaponBehavior封装起来。

  • 多用组合,少用继承

  将角色类和武器类进行组合,少用继承。

  • 针对接口编程,不针对实现编程

  实现武器的接口,并不是通过角色类自己来实现。

源码:

Character.java

 1 /**
 2  * Created by Edward on 2016/7/9.
 3  */
 4 public abstract class Character {
 5     protected WeaponBehavior weapon;
 6     public abstract void fight();
 7     public void setWeapon(WeaponBehavior weapon)
 8     {
 9         this.weapon = weapon;
10     }
11 }

WeaponBehavior.java

1 /**
2  * Created by Edward on 2016/7/9.
3  */
4 public interface WeaponBehavior {
5     void useWeapon();
6 }

King.java

1 /**
2  * Created by Edward on 2016/7/9.
3  */
4 public class King extends Character {
5     @Override
6     public void fight() {
7         this.weapon.useWeapon();
8     }
9 }

SwordBehavior.java

1 /**
2  * Created by Edward on 2016/7/9.
3  */
4 public class SwordBehavior implements WeaponBehavior {
5     @Override
6     public void useWeapon() {
7         System.out.println("use Sword!");
8     }
9 }

测试类:

 1 /**
 2  * Created by Edward on 2016/7/9.
 3  */
 4 public class Test {
 5 
 6     public static void main(String[] args) {
 7         Character king = new King();
 8         WeaponBehavior sword = new SwordBehavior();
 9         king.setWeapon(sword);
10         king.fight();
11     }
12 }

参考自《设计模式》

原文地址:https://www.cnblogs.com/one--way/p/5655927.html