当前位置:网站首页>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 .
边栏推荐
- 99% of people don't know that privatized deployment is also a permanently free instant messaging software!
- Flipping game (enumeration)
- 链式二叉树的基本操作(C语言实现)
- 手把手教姐姐写消息队列
- Micro service remote debug, nocalhost + rainbow micro service development second bullet
- Numpy——axis
- 面试唯品会实习测试岗、抖音实习测试岗【真实投稿】
- AI写首诗
- Redis
- [tpm2.0 principle and Application guide] Chapter 9, 10 and 11
猜你喜欢
Charles+drony的APP抓包
Realize payment function in applet
我感觉被骗了,微信内测 “大小号” 功能,同一手机号可注册两个微信
PV静态创建和动态创建
Redis集群与扩展
Basic operation of chain binary tree (implemented in C language)
[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
In the first half of 2022, I found 10 books that have been passed around by my circle of friends
Pasqal首席技术官:模拟量子计算率先为工业带来量子优势
Will low code help enterprises' digital transformation make programmers unemployed?
随机推荐
L1-019 who falls first (Lua)
学习open62541 --- [67] 添加自定义Enum并显示名字
Cloud security daily 220707: Cisco Expressway series and telepresence video communication server have found remote attack vulnerabilities and need to be upgraded as soon as possible
Redis publishing and subscription
L1-025 positive integer a+b (Lua)
Cadre de validation des données Apache bval réutilisé
鸿蒙智能家居【1.0】
解决rosdep的报错问题
3. About cookies
Embedded interview questions (algorithm part)
Nat address translation
POJ 1182 :食物链(并查集)[通俗易懂]
How to choose the appropriate automated testing tools?
ip netns 命令(备忘)
Comparison and selection of kubernetes Devops CD Tools
How to share the same storage among multiple kubernetes clusters
6.关于jwt
微信网页调试8.0.19换掉X5内核,改用xweb,所以x5调试方式已经不能用了,现在有了解决方案
高温火烧浑不怕,钟薛高想留清白在人间
Continuous test (CT) practical experience sharing