您现在的位置是:网站首页>文章内容文章内容

设计模式--责任链模式

李鹏2023-03-25PHP323人已围观

责任链模式是一种设计模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。

例如:公司针对请假有如下规定,组长可以审批3天(包含3天)以下的请假,4-7(包含7天)天的,由主管审批,8-15(包含15天)天的由部门经理审批,15天以上的由老板审批,用责任链模式实现,伪代码如下:

<?php

abstract class  HolidayHandleChain
{
	
	protected $leader;

	public function setLeader($leader)
	{
		$this->leader = $leader;
	}

	abstract public function handle(int $days);
}

class TeamLeaderChain extends HolidayHandleChain
{
	public function handle(int $days)
	{
		if ($days <= 3) {
			echo "您的请假申请待处理中,处理人是:团队小组长";
		}else{
			$this->leader->handle($days);
		}
	}
}

class SupervisorChain extends HolidayHandleChain
{
	public function handle(int $days)
	{
		if ($days <= 7) {
			echo "您的请假申请待处理中,处理人是:项目主管";
		}else{
			$this->leader->handle($days);
		}
	}
}

class DirectorChain extends HolidayHandleChain
{
	public function handle(int $days)
	{
		if ($days <= 15) {
			echo "您的请假申请待处理中,处理人是:部门经理";
		}else{
			$this->leader->handle($days);
		}
	}
}

class BossChain extends HolidayHandleChain
{
	public function handle(int $days)
	{
		if ($days <= 30) {
			echo "您的请假申请待处理中,处理人是:老板";
		}else{
			echo "您的请假申请被拒绝,处理人是:老板 拒绝原因:请假时间太长";
		}
	}
}

$chain1 = new TeamLeaderChain();
$chain2 = new SupervisorChain();
$chain3 = new DirectorChain();
$chain4 = new BossChain();

$chain1->setLeader($chain2);
$chain2->setLeader($chain3);
$chain3->setLeader($chain4);

$chain1->handle(20); //结果 : 您的请假申请被拒绝,处理人是:老板 拒绝原因:请假时间太长
0

文章评论

我的名片

姓名:李鹏

职业:PHP工程师

现居:广东-深圳

网址:https://www.lipeng93.cn