Unity中的策略模式

策略模式主要用于游戏中的数值计算。为不同角色的相同方法提供统一的接口。方便管理。

Unity中的策略模式_第1张图片

using UnityEngine;

public class Test : MonoBehaviour
{
    private void Start()
    {
        StrategyContext strategyContext = new StrategyContext(new ConcreteStrategyA());
        strategyContext.Do();
        strategyContext.Strategy=new ConcreteStrategyB();
        strategyContext.Do();
    }
}

public class StrategyContext
{
    private IStrategy _strategy;

    public IStrategy Strategy
    {
        get { return _strategy; }
        set { _strategy = value; }
    }

    public StrategyContext(IStrategy strategy)
    {
        _strategy = strategy;
    }

    public void Do()
    {
        _strategy.Calculate();
    }
}

public interface IStrategy
{
    void Calculate();
}

public class ConcreteStrategyA : IStrategy
{
    public void Calculate()
    {
        Debug.Log("a计算");
    }
}

public class ConcreteStrategyB : IStrategy
{
    public void Calculate()
    {
        Debug.Log("b计算");
    }
}

public class ConcreteStrategyC : IStrategy
{
    public void Calculate()
    {
        Debug.Log("c计算");
    }
}

 

你可能感兴趣的:(设计模式)