设计模式-职责链模式

职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

职责链模式好处在于可以简化对象之间的相互连接,它们只需保持一个指向其后继者的引用,而不需保持它所有的接受者的引用。
比如:一个员工的所有请求都只需告诉经理,如经理不能解决则交由总监解决。而不需要员工向总监请求。
UML:
这里写图片描述

//抽象类
class Manager
{
public:
    Manager(Manager *superior, string name) :m_superior(superior), m_name(name) {}
    virtual void RequestApplication(string name, int num) = 0;
protected:
    Manager *m_superior;    //上级
    string m_name;
};
//经理
class CommonManager:public Manager
{
public:
    CommonManager(Manager *superior, string name) :Manager(superior, name) {}
    void RequestApplication(string name, int num)
    {
        if (num <= 5)
        {
            cout << "CommonManager: " << m_name << "批准 " << name << num << " 天请假" << endl;
        }
        else
        {
            m_superior->RequestApplication(name, num);  //自己不能处理则交由上级处理
        }
    }
};
//总监
class Majordomo :public Manager
{
public:
    Majordomo(Manager *superior, string name) :Manager(superior, name) {}
    void RequestApplication(string name, int num)
    {
        if (num <= 15)
        {
            cout << "Majordomo: " << m_name << "批准 " << name << num << " 天请假" << endl;
        }
        else
        {
            m_superior->RequestApplication(name, num);
        }
    }
};
//总经理
class GeneralManager :public Manager
{
public:
    GeneralManager(Manager *superior, string name) :Manager(superior, name) {}
    void RequestApplication(string name, int num)
    {
        if (num <= 30)
        {
            cout << "GeneralManager: " << m_name << "批准 " << name << num << " 天请假" << endl;
        }
        else
        {
            cout << "GeneralManager: " << m_name << "你还是辞职吧" << endl;
        }
    }
};

int main()
{

    Manager *zonjinli = new GeneralManager(NULL, "ZonJinLi");
    Manager *zonjian = new Majordomo(zonjinli, "ZonJian");
    Manager *jinli = new CommonManager(zonjian, "JinLi");
    //请求都由经理处理,但是实际处理由具体管理类来处理,客户端不需要知道
    jinli->RequestApplication("yu", 5); 
    jinli->RequestApplication("yu", 15);
    jinli->RequestApplication("yu", 30);
    jinli->RequestApplication("yu", 40);
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值