Unity 设计模式之责任链模式-学习笔记

1.责任链模式

顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。

在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。

2.与装饰者模式的异同

相同点:

  • 装饰者模式和责任链模式都可以有任意多个装饰者/拦截器。

  • 装饰者/拦截器可以在最终处理的前/后添加自己的处理逻辑。

不同点:

  • 装饰者模式必须要有一个被装饰者,装饰者装饰被装饰者,但装饰者的类型永远不变。责任链模式是对事件的处理,重要的是处理的过程而不是返回的结果

  • 装饰者模式中任意一个装饰者都会生效,而责任链模式中部分拦截器可能没有机会处理事件。

非常好的责任链模式讲解

 3.代码实现

下面是在Unity中代码模拟测试,代码挂载在物体上就可以测试运行:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Player : MonoBehaviour, IExcute
{
	public UnityEngine.UI.Image[] images;
	public int index = 0;
	private int imaUnlockCount;
	private void Start()
	{
		BaseLevel Level1 = new Level1(this);
		BaseLevel Level2 = new Level2(this);
		BaseLevel Level3 = new Level3(this);

		Level1.SetLevel(Level2);
		Level2.SetLevel(Level3);

		Level1.Handle();

		for (var i = 0; i < imaUnlockCount; i++)
		{
			images[i].GetComponent<UnityEngine.UI.Image>().color = new Color(1, 1, 1);
		}
	}

	public int GetIndex()
	{

		return index;
	}

	public void Handle()
	{
		print(imaUnlockCount++);
	}
}

public class Level1 : BaseLevel
{
	public Level1(IExcute player) : base(player)
	{
	}

	public override void Handle()
	{
		if (player.GetIndex() >= 0)
		{
			player.Handle();
			if (baseLevel != null)
				baseLevel.Handle();
		}
	}
}
public class Level2 : BaseLevel
{
	public Level2(IExcute player) : base(player)
	{
	}

	public override void Handle()
	{
		if (player.GetIndex() >= 1)
		{
			player.Handle();
			if (baseLevel != null)
				baseLevel.Handle();
		}
	}
}
public class Level3 : BaseLevel
{
	public Level3(IExcute player) : base(player)
	{
	}

	public override void Handle()
	{
		if (player.GetIndex() >= 2)
		{
			player.Handle();
			if (baseLevel != null)
				baseLevel.Handle();
		}
	}
}
public interface IExcute
{
	int GetIndex();
	void Handle();
}
public abstract class BaseLevel
{
	protected IExcute player;
	public BaseLevel(IExcute player)
	{
		this.player = player;
	}
	protected BaseLevel baseLevel = null;
	public virtual void SetLevel(BaseLevel BL)
	{
		this.baseLevel = BL;
	}
	public abstract void Handle();

}

测试结果

测试成功!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值