学习设计模式

2,策略模式(strategy)

2017-09-21  本文已影响9人  Kenny丶Mo

1,定义

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

2,具体的代码的实现以及UML图

策略模式.png
//这是标记的符号  ````

using UnityEngine;
using System.Reflection;
using StrategyMode;

public class strategyMode : MonoBehaviour
{
    void Start()
    {
        Context context = new Context("B");
        context.GetResult();
    }
}

// factory and strategy and reflection        
namespace StrategyMode
{
    public abstract class Strategy
    {
        public abstract void AlgrithmInterface();
    }

    public class ConcreteStrategyA : Strategy
    {
        public override void AlgrithmInterface()
        {
            Debug.Log("ConcreteStrategyA");
        }
    }

    public class ConcreteStrategyB : Strategy
    {
        public override void AlgrithmInterface()
        {
            Debug.Log("ConcreteStrategyB");
        }
    }

    public class ConcreteStrategyC : Strategy
    {
        public override void AlgrithmInterface()
        {
            Debug.Log("ConcreteStrategyC");
        }
    }

    public class Context
    {
        private Strategy Strategy;

        //  strategy mode only

        //public Context(Strategy strategy)
        //{
        //    this.Strategy = strategy;
        //}


        //  strategy mode and factory mode

        //  use reflection need 

        public Context(string name)
        {
            Strategy = (Strategy)(Assembly.Load("Assembly-CSharp").
                                  CreateInstance("StrategyMode.ConcreteStrategy" + name));
        }

        public void GetResult()
        {
            Strategy.AlgrithmInterface();
        }
    }
}

3,关于策略模式的思考

策略模式是一种定义一系列算法的方法,从概念上看,所有的算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法与使用算法类之间的耦合。
策略模式不仅可以用来封装算法,也可以用来封装任何类型的规则,适用于处理需要在不同的阶段应用不同的业务规则的情况。

4,关于策略模式和简单工厂模式的区别的思考

简单工厂模式更加强调的是对象的创建,利用创建的对象去执行操作
策略模式更加强调的是通过不同的算法得到不同的结果,强调使用不同i的规则或者算法。通过context得到结果,而不是实际的对象。

上一篇 下一篇

猜你喜欢

热点阅读