行为型模式之策略模式Strategy

一、认识

策略模式Strategy:定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户

 

二、使用场景说明

Strategy:声明一个与所有支持的算法共同的接口。上下文使用此接口调用由具体策略定义的算法。

ConcreteStrategy:利用策略接口实现算法

Context:

  • 用具体策略对象配置
  • 维护对策略对象的引用
  • 可以定义允许策略访问其数据的接口。

三、基础模板代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{ 
    class Program
    {
        static void Main(string[] args)
        {
            Context context;
            context = new Context(new ConcreteStrategyA());
            context.ContextInterface();

            context = new Context(new ConcreteStrategyB());
            context.ContextInterface();

            context = new Context(new ConcreteStrategyC());
            context.ContextInterface();

            Console.WriteLine();
            Console.ReadLine();
           

        }
    }
   
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    class Context//上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
    {
        Strategy strategy;
        public Context(Strategy strategy)//初始化时,传入具体的策略对象
        {
            this.strategy = strategy;//将参数赋值给上面的Strategy的strategy
        }
        //上下文接口
        public void ContextInterface()//根据具体的策略对象,调用其算法的方法。void为不返回值的方法指定返回值类型。
        {
            strategy.AlgorithmInterface();
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{
    class ConcreteStrategyA : Strategy//具体策略类,封装了具体的算法或行为,继承于Strategy
    {
        //算法A实现方法
        public override void AlgorithmInterface()//方法重写
        {
            Console.WriteLine("算法A实现");
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 策略模式
{     //策略类,定义所有支持的算法的公共接口
     abstract class Strategy//加abstract关键字,表明是抽象类,还有抽象方法需要了解
    {   
         //抽象类不能实例化
         //抽象方法是必须被子类重写的方法
         //若类中包含抽象方法,那么类就必须定义为抽象类,不论是否包含其他一般方法
         //算法方法
        public abstract void AlgorithmInterface();
         //在方法返回值前加abstract表明此方法是抽象方法,抽象方法没有方法体,直接在括号后加“;”
    }
  
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章