Strategy策略模式_C#

一个类的行为或其算法可以在运行时更改


using UnityEngine;
using System.Collections;

namespace StrategyPatternExample2
{
    public class StrategyPatternExample2 : MonoBehaviour
    {
        Animal sparky = new Dog();
        Animal tweety = new Bird();
        void Start()
        {

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

            // change behaviour of dog
            

            
        }
        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                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、付费专栏及课程。

余额充值