标签:style blog http io color ar sp for strong
[csharp] view plaincopyprint? public abstract class Handler { protected Handler successor; public void SetSuccessor(Handler successor) { this.successor = successor; } public abstract void HandlerRequest(object request); }
具体实现类,是完整职责链的一个环节。
public class CreateHandler0 : Handler { public override void HandlerRequest(object request) { string value = request as String; Regex regex = new Regex(@"[\u4e00-\u9fa5]", RegexOptions.IgnoreCase); if (regex.IsMatch(value)) { Console.WriteLine(string.Format(@"‘{0}‘ 是汉字", value)); } else { successor.HandlerRequest(request); } } } public class CreateHandler1 : Handler { public override void HandlerRequest(object request) { string value = request as String; Regex regex = new Regex(@"^\d+$", RegexOptions.IgnoreCase); if (regex.IsMatch(value)) { Console.WriteLine(string.Format(@"{0} 是数字", int.Parse(value))); } else { successor.HandlerRequest(request); } } } public class CreateHandler2 : Handler { public override void HandlerRequest(object request) { Console.WriteLine(string.Format(@"{0} 既不是汉字也不是数字。",request)); } }
调用:
[csharp] view plaincopyprint? static void Main(string[] args) { Handler handler0 = new CreateHandler0(); Handler handler1 = new CreateHandler1(); Handler handler2 = new CreateHandler2(); handler0.SetSuccessor(handler1); handler1.SetSuccessor(handler2); string string1 = "中国"; string string2 = "110"; string string3 = "++--"; Console.WriteLine("测试:{0}",string1); handler0.HandlerRequest(string1); Console.WriteLine("测试:{0}", string2); handler0.HandlerRequest(string2); Console.WriteLine("测试:{0}", string3); handler0.HandlerRequest(string3); Console.Read(); }
这样,对请求步骤可以随时的增加或者修改,增强了处理对象的灵活性。从结构上来看有些类似于建造者模式,都是将步骤分离出来。只是建造者不需要指向后一个。
转载自:
http://blog.csdn.net/yysyangyangyangshan/article/details/7395632
标签:style blog http io color ar sp for strong
原文地址:http://www.cnblogs.com/yundan/p/4081748.html