Chain of Responsibility 責任鏈模式

package com.lonton.designpatterns;

abstract class Chain
{
	public static int ONE = 1;
	public static int TWO = 2;
	public static int THREE = 3;
	protected int threshold;
	
	protected Chain next;
	
	public void setNext(Chain chain)
	{
		next = chain;
	}
	
	public void message(String msg, int priority)
	{
		if (priority <= threshold)
		{
			writeMessage(msg);
		}
		
		if (next != null)
		{
			next.message(msg, priority);
		}
	}
	
	abstract protected void writeMessage(String msg);
}

class AA extends Chain
{
	public AA(int threshold)
	{
		this.threshold = threshold;
	}

	@Override
	protected void writeMessage(String msg)
	{
		// TODO Auto-generated method stub
		System.out.println("A: " + msg);
	}
	
}

class B extends Chain
{
	public B(int threshold)
	{
		this.threshold = threshold;
	}

	@Override
	protected void writeMessage(String msg)
	{
		// TODO Auto-generated method stub
		System.out.println("B: " + msg);
	}
	
}

class C extends Chain
{
	public C(int threshold)
	{
		this.threshold = threshold;
	}

	@Override
	protected void writeMessage(String msg)
	{
		// TODO Auto-generated method stub
		System.out.println("C: " + msg);
	}
	
}

public class ChainOfResponsibilityTest
{
	private static Chain createChain()
	{
		Chain chain1 = new AA(Chain.THREE);
		
		Chain chain2 = new B(Chain.TWO);
		chain1.setNext(chain2);
		
		Chain chain3 = new C(Chain.ONE);
		chain2.setNext(chain3);
		
		return chain1;
	}
	
	public static void main(String[] args)
	{
		Chain chain = createChain();
		
		chain.message("Level 3", Chain.THREE);
		chain.message("Level 2", Chain.TWO);
		chain.message("Level 1", Chain.ONE);				
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章