策略模式:定义了算法族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化独立于实用算法的客户。
OO原则:
封装变化。
针对接口编程,而不是针对具体实现编程。
多用组合,少用继承。
算法族
- interface IAttact
- {
- void attact();
- }
- internal class AttactWithKnife : IAttact
- {
- public void attact()
- {
- Console.WriteLine( "Attact with knife!" );
- }
- }
- internal class AttactWithBox : IAttact
- {
- public void attact()
- {
- Console.WriteLine( "Attact with box!" );
- }
- }
客户
- abstract class Character
- {
- protected IAttact At; //接口变量
- private string name;
- public string Name
- {
- get
- {
- return name;
- }
- set
- {
- this .name = value;
- }
- }
- public void fight()
- {
- if(At !=null)
- {
- At.attact();
- }
- }
- public void setfightmethod( IAttact At)
- {
- this .At = At;
- }
- }
- internal class Soldier : Character
- {
- public Soldier()
- {
- this .Name = "Soldier" ;
- }
- }
测试
- class Program
- {
- static void Main( string [] args)
- {
- Soldier a= new Soldier();
- Console.WriteLine(a.Name);
- a.setfightmethod(new AttactWithKnife());
- a.fight();
- a.setfightmethod( new AttactWithBox());
- a.fight();
- Console.ReadLine();
- }
- }