设计模式6--责任链模式(The chain of responsibility pattern)

本文通过一个具体的Java实现案例介绍了责任链设计模式的应用。该模式允许请求沿着处理者链传递,直到有一个处理者决定处理此请求。每个处理者包含对另一个处理者的引用,形成了一个链。文中展示了如何创建不同级别的帮助接口实现,并将它们串联起来处理特定类型的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果一个处理不了,就传给链上的小一个来处理。
subject notification subject1

subject-->object1-->object2-->object3


interface HelpInterface
{
	public void getHelp(int helpConstant);
}

public class FrontEnd implements HelpInterface
{
	final int FRONT_END_HELP = 1;
	HelpInterface successor;
	
	public FrontEnd(HelpInterface s)
	{
		successor = s;
	}
	
	public void getHelp(int helpConstant)
	{
		if(helpConstant != FRONT_END_HELP) {
			successor.getHelp(helpConstant);
		} else {
			System.out.println("This is the front end.");
		}
	} 
}
public class IntermediateLayer implements HelpInterface
{
	final int INTERMEDIATE_LAYER_HELP = 2;
	HelpInterface successor;
	
	public FrontEnd(HelpInterface s)
	{
		successor = s;
	}
	
	public void getHelp(int helpConstant)
	{
		if(helpConstant != INTERMEDIATE_LAYER_HELP) {
			successor.getHelp(helpConstant);
		} else {
			System.out.println("This is the IntermediateLayer.");
		}
	} 
}

public class Application implements HelpInterface
{			
	public Application()
	{
	}
	
	public void getHelp(int helpConstant)
	{	
		System.out.println("This is the MegaGigaCo application.");		
	} 
}

public class TestHelp
{
	public static void main(String args[])
	{
		final int FRONT_END_HELP = 1;
		final int INTERMEDIATE_LAYER_HELP = 2;
		final int GENERAL_HELP = 3;
		
		Application app = new Application();
		
		IntermediateLayer intermediateLayer = new IntermediateLayer(app);
		
		FrontEnd frontEnd = new FrontEnd(intermediateLayer);
		
		frontEnd.getHelp(GENERAL_HELP);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值