随笔-42  评论-128  文章-0  trackbacks-4
VS 2008

多个对象构成一个链式结构,客户端向链中的某个对象发出请求,被请求的对象可以处理客户代码的请求,也可以根据业务将请求向下传递,依此类推,直到请求最终被某对象处理,或抛出异常。这就是职责链模式的应用场景。

1. 模式UML图



2. 代码示例

    例子仅为演示职责链模式。
    软件从业人员,可能分SE, SSE, PL, PM等不同级别,有些工作可能按工作性质需要不同级别的人员才能处理,对于自己不能处理的工作,那么,他需要将请求传递给下家。



IWorker.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {

    
public interface IWorker {

        
void DoWork(int level);
    }

}


SE.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
    
public class SE : IWorker {

        
private IWorker next;

        
public SE(IWorker next) {
            
this.next = next;
        }


        
IWorker Members
    }

}


SSE.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
    
public class SSE : IWorker {

        
private IWorker next;

        
public SSE(IWorker next) {
            
this.next = next;
        }


        
IWorker Members
    }

}


PL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
    
public class PL : IWorker {

        
private IWorker next;

        
public PL(IWorker next) {
            
this.next = next;
        }


        
IWorker Members
    }

}


PM.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.ChainOfResponsibility.BLL {
    
public class PM : IWorker {

        
private IWorker next;

        
public PM(IWorker next) {
            
this.next = next;
        }


        
IWorker Members
    }

}


Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DesignPattern.ChainOfResponsibility.BLL;

namespace DesignPattern.ChainOfResponsibility {
    
class Program {
        
static void Main(string[] args) {

            IWorker worker 
= new SE(new SSE(new PL(new PM(null))));
            worker.DoWork(
3);
        }

    }

}


Output

posted on 2008-04-01 21:34 Tristan(GuoZhijian) 阅读(178) 评论(3)  编辑 收藏 所属分类: Design Pattern

评论:
#1楼  2008-04-22 02:41 | 睿 [未注册用户]
整体上它让我明白那些 Design Pattern 的特性这让我很高兴也很感谢你的帮忙(毕竟在这之前我一直不太了解那些英文版本的注解)。

还有若是能加上一些资料那会更好,比如:该Design Pattern的利与弊和在那种情况下我们会需要用到它。

最后一样,为什么我没有我需要的Command Design Pattern....
  回复  引用    
#2楼 [楼主] 2008-04-22 14:22 | Tristan(Guozhijian)      
@睿

啊,我也是把我理解的写下来,欢迎讨论,互相提高

这个系列还没有写完
你提到的Command模式,可能是下一篇,最近忙于研究jQuery,所以一段时间没有更新模式的内容了
  回复  引用  查看    
#3楼  2008-05-13 16:45 | 吉日嘎拉 [未注册用户]
16个模式,我从头看到了尾巴,记住了好几个,
接着也背一背,今天没白过,学了你的设计模式。
一直设置为IE的首页,总算都看了一遍了。
  回复  引用    

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
"五向定位"职业成长路线公开课(上海、南京、大连)
Google站内搜索


相关链接: