디자인 모델 ChainOf Responsibility

2347 단어
/**********************************************************************
*	Chain of Responsibility
*
* definition
*		Avoid coupling the sender of a request to its receiver by giving more 
*		than one object a chance to handle the request. Chain the receiving 
*		objects and pass the request along the chain until an object handles it. 
*   
*		  
*	   http://www.dofactory.com/Patterns/PatternChain.aspx#_self1
* 
***********************************************************************/
using System;

namespace Pattern.ChainOfResponsibility
{
	public class MainApp
	{
		public static void Main()
		{
			Handler ha = new ConcreteHandlerA();
			Handler hb = new ConcreteHandlerB();
			Handler hc = new ConcreteHandlerC();
			
			ha.SetChain(hb);
			hb.SetChain(hc);
			
			Man scott = new Man(21);
			
			ha.HandlerRequest(scott);
			
			Console.ReadKey();
		}
	}
	// handler of object
	class Man
	{
		private int _age;
		
		public Man(int age)
		{
			_age = age;
			//Console.WriteLine("Man: {0}",_age);
		}
		
		public int Age
		{
			get{return _age;}
			set{_age = value;}
		}
	}
	
	
	// Handler Chain
	abstract class Handler
	{
		protected Handler chain;
		
		public void SetChain(Handler handler)
		{
			this.chain = handler;
		}
		
		public abstract void HandlerRequest(Man m);
	}
	
	class ConcreteHandlerA : Handler
	{
		public override void HandlerRequest(Man m)
		{
			//Console.WriteLine("ConcreteHandlerA.Man.age = {0}",m.Age);
			if(m.Age>=0&&m.Age<=10)
			{
				Console.WriteLine(this.GetType().Name+ " handler " + m.Age);
			}
			else
			{
				if(chain != null)
					chain.HandlerRequest(m); // pass to next handler
			}
		}
	}
	
	class ConcreteHandlerB : Handler
	{
		public override void HandlerRequest(Man m)
		{
			if(m.Age>10&&m.Age<=20)
			{
				Console.WriteLine(this.GetType().Name+ " handler " + m.Age);
			}
			else
			{
				if(chain != null)
					chain.HandlerRequest(m); // pass to next handler
			}
		}
	}
	
	class ConcreteHandlerC : Handler
	{
		public override void HandlerRequest(Man m)
		{
			if(m.Age>20&&m.Age<=30)
			{
				Console.WriteLine(this.GetType().Name+ " handler " + m.Age);
			}
			else
			{
				if(chain != null)
					chain.HandlerRequest(m); // pass to next handler
			}
		}
	}
	
	
}

좋은 웹페이지 즐겨찾기