当前位置:网站首页>Responsibility chain model - unity

Responsibility chain model - unity

2022-07-07 19:17:00 Just be interesting

The chain of responsibility model

The responsibility chain model is an object behavior model , In this mode The request sent by the requester needs to be passed along the handler chain , And be handled by the handler , This avoids coupling the request sender with multiple processors .

In the chain of responsibility , Separate the behavior of processing requests into objects , Connect all behaviors through the structure of the chain . Such a structure is very common , Such as the bank's business process , Company procurement process, etc , They all belong to such a structure . There is a more common form , When the handler accepts the request , You can decide whether to handle it or leave it to the next handler , There can be at most one handler for each requester , Or there is no handler .

structure

 Insert picture description here

explain

  • Abstract processor (Handler)- Define all interfaces for processing requests , It also contains a subsequent connection .
  • Basic processor (Base Handler, Optional )- Extract the public part of the code of all specific processors , Such as execution judgment , perform , Set the next successor point, etc , It is to improve the code reuse rate .
  • Specific handler (Concrete Handler)- Implement the method of request processing , Judge whether to process this request , Whether to pass the request to the next successor .

Realization

Release different skills according to anger value .

Skill enumeration

    public enum AngerSkill
    {
    
        None,
        One,
        Two,
        Three,
    }

Processor interface

    public interface IHandler
    {
    
        IHandler NextHandler {
     set; }

        AngerSkill Release(int angleValue);
    }

Basic processor

    public abstract class BaseHandler : IHandler
    {
    
        private IHandler _nextHandler;
		
		// Implement the successor node method 
        public IHandler NextHandler
        {
    
            set => _nextHandler = value;
        }
        
        // Using the template method pattern , Define algorithm flow , The concrete implementation is allocated to subclasses 
        public AngerSkill Release(int angerValue)
        {
    
            if (IsAllow(angerValue))
                return Realization();
            return _nextHandler?.Release(angerValue) ?? AngerSkill.None;
        }
		
		// Ways to achieve behavior 
        protected abstract AngerSkill Realization();
        // Conditions for judging whether this behavior can be performed 
        protected abstract bool IsAllow(int angerValue);
    }

Skill handlers - Specific handler

	// Skill 1 
    public class AngerSkillOne : BaseHandler
    {
    
        protected override AngerSkill Realization() => AngerSkill.One;

        protected override bool IsAllow(int angerValue) => angerValue > 10 && angerValue < 30;
    }
    // Skill 2 
    public class AngerSkillTwo : BaseHandler
    {
    
        protected override AngerSkill Realization() => AngerSkill.Two;

        protected override bool IsAllow(int angerValue) => angerValue >= 30 && angerValue < 60;
    }
    // Skill 3 
    public class AngerThree : BaseHandler
    {
    
        protected override AngerSkill Realization() => AngerSkill.Three;

        protected override bool IsAllow(int angerValue) => angerValue >= 60;
    }

Skill factory ( Responsible for creating , Generate a chain of responsibility , Connect related nodes )

    public class AngerSkillFactory
    {
    
        public static IHandler CreateSkill()
        {
    
            IHandler skill1 = new AngerSkillOne();
            IHandler skill2 = new AngerSkillTwo();
            IHandler skill3 = new AngerThree();

            skill1.NextHandler = skill2;
            skill2.NextHandler = skill3;

            return skill1;
        }
    }

Calling end

    public class  ResponsibiltyExample : MonoBehaviour
    {
    
        private IHandler _skill;
        private InputField _inputField;
        private TMP_Text _text;

        private void Awake()
        {
    
            _skill = AngerSkillFactory.CreateSkill();
            _inputField = GetComponentInChildren<InputField>();
            _text = GetComponentInChildren<TMP_Text>();

            _inputField.onEndEdit.AddListener(ActivateSkills);
        }

        private void ActivateSkills(string angerValue)
        {
    
            if (!int.TryParse(angerValue, out int value)) return;

            var angerSkill = _skill.Release(value);
            _text.text = angerSkill switch
            {
    
                AngerSkill.None => "Lack Of Anger",
                AngerSkill.One => "Skill One",
                AngerSkill.Two => "Skill Two",
                AngerSkill.Three => "Skill Three",
                _ => throw new ArgumentOutOfRangeException()
            };
        }
    }

 Insert picture description here  Insert picture description here

Application scenarios

  • When a request needs to be processed by multiple processors , Belong to a pair of amorous situations , Use the responsibility chain model .
  • When it is necessary to process in order .
  • Processors and processing order need to be changed dynamically
  • The request is executed by a handler , But there are multiple processors , The request needs to find an executable handler on the chain .

Advantages and disadvantages

advantage

  • You are free to choose the execution process ( A bit like a linked list )
  • The classes that initiate and execute operations are decoupled , Principle of single responsibility
  • There is no need to modify the client , Then add new responsibilities , Opening and closing principle

shortcoming

  • Some requests may not be processed
  • For a long chain of responsibility , Request processing involves multiple processing objects , The system speed decreases

Relationship with other models

  • Responsibility chain And command It is the connection between the requester and the implementer . The chain of responsibility is one to many , Dynamically deliver the request to every possible handler , Until it is processed or finished . The command is a one-to-one one one-way connection , And through parameterized commands , To flexibly handle the behavior of requesters and implementers .
  • Responsibility chain and decorate Class structure is very similar , Both are dependent combinations that pass execution operations to a series of objects . The object of responsibility chain is independent , And the delivery can be stopped at any time . Decorating objects is the behavior of extending the original method , And can't interrupt .
  • Responsibility chain and Combine Use patterns together , The request can be passed along the chain containing all the parent components to the bottom of the object tree .
  • The connection of responsibility chain can use Factory mode Create
  • Responsibility chain and Template method Use it together , You can extract the public process behavior of the handler , Improve code reuse .
原网站

版权声明
本文为[Just be interesting]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071515233507.html