策略模式

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

OO原则:

封装变化。

针对接口编程,而不是针对具体实现编程。

多用组合,少用继承。

 

算法族

  1.      interface IAttact
  2.     {
  3.          void  attact();
  4.     }
  5.      internal   class  AttactWithKnife : IAttact
  6.     {
  7.          public   void  attact()
  8.         {
  9.             Console.WriteLine( "Attact with knife!" );
  10.         }
  11.     }
  12.      internal   class  AttactWithBox : IAttact
  13.     {
  14.          public   void  attact()
  15.         {
  16.             Console.WriteLine( "Attact with box!" );
  17.         }
  18.     }

客户

  1.      abstract   class  Character
  2.     {
  3.          protected IAttact At; //接口变量
  4.          private   string  name;
  5.          public   string  Name 
  6.         { 
  7.              get
  8.             { 
  9.                  return  name;
  10.             }
  11.              set  
  12.             { 
  13.                  this .name = value; 
  14.             } 
  15.         }
  16.          public   void  fight()
  17.         {
  18.             if(At !=null)
  19.             {
  20.             At.attact();
  21.             }
  22.         }
  23.          public   void  setfightmethod( IAttact At)
  24.         {
  25.              this .At = At;
  26.         }
  27.     }
  28.      internal   class  Soldier : Character
  29.     {
  30.          public  Soldier()
  31.         {
  32.              this .Name =  "Soldier" ;
  33.         }
  34.     }

测试

  1.      class  Program
  2.     {
  3.          static   void  Main( string [] args)
  4.         {
  5.             Soldier a=  new  Soldier();
  6.             Console.WriteLine(a.Name);
  7.             a.setfightmethod(new  AttactWithKnife());
  8.             a.fight();
  9.             a.setfightmethod( new  AttactWithBox());
  10.             a.fight();
  11.             Console.ReadLine();
  12.         }
  13.     }

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值