当前位置:网站首页>Responsibility chain model - unity
Responsibility chain model - unity
2022-07-07 19:17:00 【Just be interesting】
List of articles
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

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()
};
}
}


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 .
边栏推荐
- Embedded interview questions (algorithm part)
- Short selling, overprinting and stock keeping, Oriental selection actually sold 2.66 million books in Tiktok in one month
- AI来搞财富分配比人更公平?来自DeepMind的多人博弈游戏研究
- 我感觉被骗了,微信内测 “大小号” 功能,同一手机号可注册两个微信
- AI writes a poem
- 2022.07.05
- [information security laws and regulations] review
- 2022.07.02
- [software test] from the direct employment of the boss of the enterprise version, looking at the resume, there is a reason why you are not covered
- [Base64 notes] [suggestions collection]
猜你喜欢
随机推荐
For friends who are not fat at all, nature tells you the reason: it is a genetic mutation
[tpm2.0 principle and Application guide] Chapter 16, 17 and 18
编译原理 实验一:词法分析器的自动实现(Lex词法分析)
AI写首诗
The live broadcast reservation channel is open! Unlock the secret of fast launching of audio and video applications
[information security laws and regulations] review
Embedded interview questions (algorithm part)
Three forms of multimedia technology commonly used in enterprise exhibition hall design
POJ 2392 Space Elevator
The top of slashdata developer tool is up to you!!!
How many are there (Lua)
How to choose the appropriate automated testing tools?
ip netns 命令(备忘)
Draw squares with Obama (Lua)
Wechat web debugging 8.0.19 replace the X5 kernel with xweb, so the X5 debugging method can no longer be used. Now there is a solution
Mathematical analysis_ Notes_ Chapter 11: Fourier series
Redis cluster and expansion
Tips and tricks of image segmentation summarized from 39 Kabul competitions
Big Ben (Lua)
POJ 2392 Space Elevator



![[Tawang methodology] Tawang 3W consumption strategy - U & a research method](/img/63/a8c08ac6ec7d654159e5fc8b4423e4.png)





