当前位置:网站首页>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 .
边栏推荐
- Tapdata 的 2.0 版 ,开源的 Live Data Platform 现已发布
- AI writes a poem
- Hongmeng smart home [1.0]
- 3.关于cookie
- 微服务远程Debug,Nocalhost + Rainbond微服务开发第二弹
- First time in China! The language AI strength of this Chinese enterprise is recognized as No.2 in the world! Second only to Google
- ES6笔记一
- Flipping Game(枚举)
- Comparison and selection of kubernetes Devops CD Tools
- 5billion, another master fund was born in Fujian
猜你喜欢

网易云信参与中国信通院《实时音视频服务(RTC)基础能力要求及评估方法》标准编制...

數據驗證框架 Apache BVal 再使用

Review of network attack and defense

Reuse of data validation framework Apache bval

前首富,沉迷种田

博睿数据入选《2022爱分析 · IT运维厂商全景报告》

【软件测试】从企业版BOSS直聘,看求职简历,你没被面上是有原因的
![[tpm2.0 principle and Application guide] Chapter 9, 10 and 11](/img/7f/0d4d91142bc3d79ea445a8f64afba7.png)
[tpm2.0 principle and Application guide] Chapter 9, 10 and 11

我感觉被骗了,微信内测 “大小号” 功能,同一手机号可注册两个微信

【牛客网刷题系列 之 Verilog进阶挑战】~ 多bit MUX同步器
随机推荐
企业MES制造执行系统的分类与应用
In the first half of 2022, I found 10 books that have been passed around by my circle of friends
Creative changes brought about by the yuan universe
Numpy——axis
我感觉被骗了,微信内测 “大小号” 功能,同一手机号可注册两个微信
Continuous test (CT) practical experience sharing
Learn open62541 -- [67] add custom enum and display name
How to implement safety practice in software development stage
A hodgepodge of ICER knowledge points (attached with a large number of topics, which are constantly being updated)
unity2d的Rigidbody2D的MovePosition函数移动时人物或屏幕抖动问题解决
最长公共前缀(leetcode题14)
[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
Realize payment function in applet
Review of network attack and defense
国内首次!这家中国企业的语言AI实力被公认全球No.2!仅次于谷歌
6. About JWT
[Tawang methodology] Tawang 3W consumption strategy - U & a research method
IP netns command (memo)
Scientists have observed for the first time that the "electron vortex" helps to design more efficient electronic products
App capture of charles+postern