用Unity写设计模式-策略模式

这篇博客介绍了策略模式,展示了如何通过该模式在运行时动态改变对象的行为。通过案例1,用排序策略展示了如何在不同的排序算法(如快速排序、Shell排序和合并排序)之间切换。案例2中,通过动物飞翔行为的不恰当实现引出问题,然后使用策略模式进行改进,实现了飞行能力的动态设置,使得代码更加灵活和可维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

策略模式介绍

定义一组算法,将每个算法都封装起来,并且使它们之间可以互换

策略模式

using UnityEngine;
using System.Collections;

namespace StrategyStructure
{
    public class StrategyStructure : MonoBehaviour
    {
	    void Start ( )
        {
            Context context;

            // Three contexts following different strategies
            context = new Context(new ConcreteStrategyA());
            context.ContextInterface();

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

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

    /// <summary>
    /// The 'Strategy' abstract class
    /// </summary>
    abstract class Strategy
    {
        public abstract void AlgorithmInterface();
    }

    /// <summary>
    /// A 'ConcreteStrategy' class
    /// </summary>
    class ConcreteStrategyA : Strategy
    {
        public override void AlgorithmInterface()
        {
            Debug.Log("Called ConcreteStrategyA.AlgorithmInterface()");
        }
    }

    /// <summary>
    /// A 'ConcreteStrategy' class
    /// </summary>
    class ConcreteStrategyB : Strategy
    {
        public override void AlgorithmInterface()
        {
            Debug.Log("Called ConcreteStrategyB.AlgorithmInterface()");
        }
    }

    /// <summary>
    /// A 'ConcreteStrategy' class
    /// </summary>
    class ConcreteStrategyC : Strategy
    {
        public override void AlgorithmInterface()
        {
            Debug.Log("Called ConcreteStrategyC.AlgorithmInterface()");
        }
    }

    /// <summary>
    /// The 'Context' class
    /// </summary>
    class Context
    {
        private Strategy _strategy;

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

        public void ContextInterface()
        {
            _strategy.AlgorithmInterface();
        }
    }
}

策略模式案例1

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

//这段真实的代码演示了Strategy模式,它以排序对象的形式封装了排序算法。  
//这允许客户端动态改变排序策略,包括快速排序,Shellsort和合并排序。  

namespace StrategyPatternExample1
{
    public class StrategyPatternExample1 : MonoBehaviour
    {
        void Start()
        {
            // Two contexts following different strategies
            SortedList studentRecords = new SortedList();

            studentRecords.Add("Samual");
            studentRecords.Add("Jimmy");
            studentRecords.Add("Sandra");
            studentRecords.Add("Vivek");
            studentRecords.Add("Anna");

            studentRecords.SetSortStrategy(new QuickSort());
            studentRecords.Sort();

            studentRecords.SetSortStrategy(new ShellSort());
            studentRecords.Sort();

            studentRecords.SetSortStrategy(new MergeSort());
            studentRecords.Sort();

        }
    }

    /// <summary>
    /// The 'Strategy' abstract class
    /// </summary>
    abstract class SortStrategy
    {
        public abstract void Sort(List<string> list);
    }

    /// <summary>
    /// A 'ConcreteStrategy' class
    /// </summary>
    class QuickSort : SortStrategy
    {
        public override void Sort(List<string> list)
        {
            list.Sort(); // Default is Quicksort
            Debug.Log("-------QuickSorted list------- ");
        }
    }

    /// <summary>
    /// A 'ConcreteStrategy' class
    /// </summary>
    class ShellSort : SortStrategy
    {
        public override void Sort(List<string> list)
        {
            //list.ShellSort(); not-implemented
            Debug.Log("-------ShellSorted list------- ");
        }
    }

    /// <summary>
    /// A 'ConcreteStrategy' class
    /// </summary>
    class MergeSort : SortStrategy
    {
        public override void Sort(List<string> list)
        {
            //list.MergeSort(); not-implemented
            Debug.Log("-------MergeSorted list------- ");
        }
    }

    /// <summary>
    /// The 'Context' class
    /// </summary>
    class SortedList
    {
        private List<string> _list = new List<string>();
        private SortStrategy _sortstrategy;

        public void SetSortStrategy(SortStrategy sortstrategy)
        {
            this._sortstrategy = sortstrategy;
        }

        public void Add(string name)
        {
            _list.Add(name);
        }

        public void Sort()
        {
            _sortstrategy.Sort(_list);
            // Iterate over list and display results
            foreach (string name in _list)
            {
                Debug.Log(" " + name);
            }
        }
    }
}

策略模式案例2

策略模式案例-不良代码演示

using UnityEngine;
using System.Collections;

public class Animal_BadExample
{
	// bad code:
	public virtual void Fly()
	{
		Debug.Log ("Can Fly");
	}
}

public class Dog_BadExample : Animal_BadExample
{
	// bad code:
	public override void Fly()
	{
		// override
	}
}

public class Cat_BadExample : Animal_BadExample
{
	// bad code:
	public override void Fly()
	{
		// override
	}
}

public class Bird_BadExample : Animal_BadExample
{
	public override void Fly()
	{
	}
}

// 记住:  
// 要
//删除重复的代码  
//消除允许一个类影响其他类的因素

策略模式案例-正确代码

using UnityEngine;
using System.Collections;

namespace StrategyPatternExample2
{
    public class StrategyPatternExample2 : MonoBehaviour
    {
        void Start()
        {
            // create dog and bird example objects
            Animal sparky = new Dog();
            Animal tweety = new Bird();

            Debug.Log("Dog: " + sparky.TryToFly());
            Debug.Log("Bird: " + tweety.TryToFly());

            // change behaviour of dog
            sparky.SetFlyingAbility(new ItFlys());

            Debug.Log("Dog: " + sparky.TryToFly());
            Debug.Log("Bird: " + tweety.TryToFly());
        }
    }


    // Using Interfaces for decoupling
    // putting behaviour that varies in different classes
    public interface IFly
    {
        string Fly();
    }

    // Class that holds behaviour for objects that can fly
    class ItFlys : IFly
    {
        public string Fly()
        {
            return "Flying high";
        }
    }

    // Class that holds behaviour for objects that can not fly
    class CantFly : IFly
    {
        public string Fly()
        {
            return "I can't fly";
        }
    }

    class FlyingSuperFast : IFly
    {
        public string Fly()
        {
            return "Fly super fast";
        }
    }


    // Classes that hold an instance of the behaviours above:
    public class Animal
    {
        // hereby adding the behaviour
        // it also can change that way
        public IFly flyingType;

        public string TryToFly()
        {
            return flyingType.Fly();
        }

        public void SetFlyingAbility(IFly newFlyingType)
        {
            this.flyingType = newFlyingType;
        }
    }

    // derived objects that vary from the base Animal:
    public class Dog : Animal
    {
        public Dog()
        {
            flyingType = new CantFly();
        }
    }

    public class Bird : Animal
    {
        public Bird()
        {
            flyingType = new ItFlys();
        }
    }
}

// 记住:  
// 要
//删除重复的代码  
//消除允许一个类影响其他类的因素
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值