Strategy模式

上个周末开始看head first,这本书通俗易懂,非常适合学习设计模式。
感觉看了后而不去用很难深刻的理解设计模式,所以就把其中的例子实现了一下,加深理解。底下为strategy模式的一个小例子。
  1. package strategyPattern;
  2. /**
  3.  * strategy Pattern
  4.  * @author Zheng Haitao
  5.  *
  6.  */
  7. public class Character {
  8.     private IweaponBehavior weaponBehavior;
  9.     public Character(IweaponBehavior weaponBehavior){
  10.         this.weaponBehavior = weaponBehavior;
  11.     }
  12.     public void setWeaponBehavior(IweaponBehavior weaponBehavior){
  13.         this.weaponBehavior = weaponBehavior;
  14.     }
  15.     
  16.     public void fight(){
  17.         weaponBehavior.useWeapon();
  18.     }
  19.     public static void main(String[] args){
  20.         
  21.         //use relevant behavior to construct character.
  22.         Character king = new King(new KnifeBehavior());
  23.         Character queen = new Queen(new GunBehavior());
  24.         
  25.         //call the wrapper method.
  26.         king.fight();
  27.         queen.fight();
  28.         
  29.         //use set method to change the behavior dynamically.
  30.         king.setWeaponBehavior(new GunBehavior());
  31.         king.fight();
  32.     }
  33. }
  34. class King extends Character{
  35.     public King(IweaponBehavior weaponBehavior){
  36.         super(weaponBehavior);
  37.     }
  38. }
  39. class Queen extends Character{
  40.     public Queen(IweaponBehavior weaponBehavior){
  41.         super(weaponBehavior);
  42.     }
  43. }
  44. //weapon behavior interface.
  45. interface IweaponBehavior{
  46.     public void useWeapon();
  47. }
  48. class KnifeBehavior implements IweaponBehavior{
  49.     @Override
  50.     public void useWeapon() {
  51.         System.out.println("this is knife behavior");
  52.     }
  53. }
  54. class GunBehavior implements IweaponBehavior{
  55.     @Override
  56.     public void useWeapon() {
  57.         System.out.println("this is gun behavior");     
  58.     }
  59. }
我就不在此介绍什么是strategy模式了,大家可以而查阅该书,讲解特别精辟。
我的理解是,strategy模式其实就是把具有共同行为的事物的特性抽象出来,然后面向接口编程,而忽略各个事物的细节。
对上例而言,其把各个角色总结抽象为character类,而把所有武器抽象为IweaponBehavior接口,这样我们在实现的时候,只要知道某个character使用某个IweaponBehavior而已,然后在运行时动态的调用他们各自的方法。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值