3.策略模式

2018-10-19  本文已影响0人  卡布萨岛

原理

在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变context 对象的执行算法。

意图

定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。

主要解决

在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护

应用实例:

1、诸葛亮的锦囊妙计,每一个锦囊就是一个策略。 2、旅行的出游方式,选择骑自行车、坐汽车,每一种旅行方式都是一个策略。

Program.cs

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 c = new Context("A");
            c.GetResult();

            Context b = new Context("B");
            b.GetResult();

            Console.ReadKey();
        }
    }
}

Strategy.cs

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

namespace 策略模式
{
    //策略和简单工厂结合
    class Context
    {
        Strategy st = null;
        public Context(string type)
        {
            switch (type)
            {
                case "A":
                            st = new ConcreteStartegyA();
                    break;
                case "B":
                            st = new ConcreteStartegyB();
                    break;
                case "C":
                            st = new ConcreteStartegyC();
                    break;
            }
        }

        public void GetResult()
        {
            st.AlgorithmInterface();
        }
    }

    //抽象算法类
    abstract class Strategy
    {
        //算法方法
        public abstract void AlgorithmInterface();
    }
    //具体算法A
    class ConcreteStartegyA : Strategy
    {
        //算法A实现方法
        public override void AlgorithmInterface()
        {
            Console.WriteLine("算法A实现");
        }
    }
    //具体算法B
    class ConcreteStartegyB : Strategy
    {
        //算法B实现方法
        public override void AlgorithmInterface()
        {
            Console.WriteLine("算法B实现");
        }
    }
    //具体算法C
    class ConcreteStartegyC : Strategy
    {
        //算法C实现方法
        public override void AlgorithmInterface()
        {
            Console.WriteLine("算法C实现");
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读