设计模式学习-行为模式-职责链模式

来源:互联网 发布:知乎 055驱逐舰 编辑:程序博客网 时间:2024/06/13 03:39

所有的人写模式,都是从创建模式开始,然后是结构模式,然后是行为模式。我想倒而为之。然而所有的模式都是用英文描述的,有时候再换成中文去描述这些模式真的很别扭。我只能尽量的详细的描述每个模式,再配上更多的使用案例,和复杂的案例。

 

chain of Responsibility:

 

目的:

 

可以把请求者与接收处理者分开。而请求的处理对象可能有多个,这样每一个请求都被自动的由一串的接收者处理。当一个对象不处理这个请求时,它会自动传给下一个对象处理。直到有一个对象处理了这个请求,或者所有的处理对象被遍历完全。

 

 

                              request process

 

 

          Encapsulate the processing elements inside a “pipeline” abstraction

 

the class diagram:

 

 

the example of c++ code:

 

#include <iostream>

#include <vector>

#include <ctime>

using namespace std;

class Base

{

    Base *next; // 1. "next" pointer in the base class

   public: Base()

   {

         next = 0;

   }

  void setNext(Base *n)

  {

      next = n;

  }

  void add(Base *n)

  {

       if (next)

       next->add(n);

      else

      next = n;

  } // 2. The "chain" method in the base class always delegates to the next obj

  virtual void handle(int i)

  {

       next->handle(i);

  }

};

 

 

class Handler1: public Base

{

  public:

     /*virtual*/void handle(int i)

    {

        if (rand() % 3)

        {

            // 3. Don't handle requests 3 times out of 4

            cout << "H1 passsed " << i << "  ";

            Base::handle(i); // 3. Delegate to the base class

        }

        else

          cout << "H1 handled " << i << "  ";

    }

};

 

 

class Handler2: public Base

{

  public:

     /*virtual*/void handle(int i)

    {

        if (rand() % 3)

        {

            cout << "H2 passsed " << i << "  ";

            Base::handle(i);

        }

        else

          cout << "H2 handled " << i << "  ";

    }

};

 

class Handler3: public Base

{

  public:

     /*virtual*/void handle(int i)

    {

        if (rand() % 3)

        {

            cout << "H3 passsed " << i << "  ";

            Base::handle(i);

        }

        else

          cout << "H3 handled " << i << "  ";

    }

};

 

int main()

{

  srand(time(0));

  Handler1 root;

  Handler2 two;

  Handler3 thr;

  root.add(&two);

  root.add(&thr);

  thr.setNext(&root);

  for (int i = 1; i < 10; i++)

  {

    root.handle(i);

    cout << '/n';

  }

}

 

上面是一个职责链的一个简单的例子,基类负责把消息传递给下一个对象处理,而子类可以定义自己的消息处理函数,或者不处理把消息传递给下一个对象。对于这个模式应用的最经典的例子,应该是windows系统下的消息传递机制。这个可以参照侯捷老师的windows程序设计。那里很详细的介绍了windows消息处理。

 

原创粉丝点击