zoukankan      html  css  js  c++  java
  • 设计模式之职责链模式(Chain of Responsibility)

    职责链模式原理:

    职责链模式和装饰模式以及组合模式类似的地方是都维持着指向父类的指针,

    不同点是职责链模式每个子类都继承父类的指针及每个之类都维持着指向父类的指针,而组合模式与装饰模式是组合类鱼装饰类维持着指向父类的指针。

    代码如下:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Manager
    {
    public:
    	Manager(string name,Manager* pmanager = NULL):m_name(name),m_pmanager(pmanager){}
    	virtual void  dealSalary(string name,int num){}
    protected:
    	Manager *m_pmanager;
    	string m_name;
    };
    
    class ComonManager:public Manager
    {
    public:
    	ComonManager(string name,Manager *pmanager):Manager(name,pmanager){}
    	virtual void  dealSalary(string name,int num)
    	{
    		if (num < 300)
    		{
    			cout << "经理"<<m_name<<"批准了"<<name<<num<<"元的工资"<<endl;
    		}
    		else
    		{
    			m_pmanager->dealSalary(name,num);
    		}
    	}
    };
    
    class MidManager:public Manager
    {
    public:
    	MidManager(string name,Manager *pmanager):Manager(name,pmanager){}
    	virtual void  dealSalary(string name,int num)
    	{
    		if (num < 500)
    		{
    			cout << "总监"<<m_name<<"批准了"<<name<<num<<"元的工资"<<endl;
    		}
    		else
    		{
    			m_pmanager->dealSalary(name,num);
    		}
    	}
    };
    
    
    class GeneralManager:public Manager
    {
    public:
    	GeneralManager(string name,Manager *pmanager):Manager(name,pmanager){}
    	virtual void  dealSalary(string name,int num)
    	{
    		cout << "总经理"<<m_name<<"批准了"<<name<<num<<"元的工资"<<endl;
    	}
    };
    
    
    int main()
    {
    	Manager* pgeneral = new GeneralManager("A",NULL);
    	Manager* pmiddle = new MidManager("B",pgeneral);
    	Manager* pcommon = new ComonManager("C",pmiddle);
    	pcommon->dealSalary("D",200);
    	pcommon->dealSalary("E",400);
    	pcommon->dealSalary("F",1000);
    	return 0;
    }
    
  • 相关阅读:
    棋盘问题 简单搜索DFS
    Equivalent Strings
    素数环
    LeetCode Maximum Product Subarray
    UVA 725 – Division
    矩形嵌套问题
    ACM最大子串和问题
    ACM装箱问题
    ACM田胫赛马
    ACM雷达安放问题
  • 原文地址:https://www.cnblogs.com/liuweilinlin/p/3207437.html
Copyright © 2011-2022 走看看